Mike Mike - 3 months ago 13
HTML Question

HTML pop-up from button click

I have a website that I want to click a button and have a pop-up to confirm if the user wants to proceed or not. I've seen several questions that use a link and have some kind of pop-up, but none that have a button with a pop-up. I've tried a few things, but they don't work the way that I want them to. Currently I have:

<p>Copy website files from MAFINFWWWPV02 to MAFINFWWWPV01</p>
<form action='Admin.php' enctype='multipart/form-data' method='post' onclick="myFunction()">
<input type='hidden' name='action' value='CopyFiles'/>
<p><input type='submit' name='submit' value='Copy Files'/></p>
</form>
<p id="demo"></p>


and then this:

<script>
function myFunction()
{
/*alert("Pressed a button did you?");*/
var x;
if (confirm("Copy all files?") == true)
{
x = "You pressed OK!";/*Want this to run the .bat*/
}
else
{
x = "You pressed Cancel!";/*Want this to not run the .bat*/
}
document.getElementById("demo").innerHTML = x;
}




This will run a .bat file. It does this regardless of whether I have clicked the 'Ok' or 'Cancel' button. I want to click 'Ok' and have the .bat run or click the 'Cancel' and not have it run. I don't know how to stop it from running.

I have a
switch($_REQUEST['action'])
in my code that looks for the 'action' from the buttons on the page. For this
case
it does this:

case 'CopyFiles':
$script = chr(92) . chr(92) . 'MAFINFWWWPV02\D$\WebContent\engsys.corp.ftr.com\BatchFiles\CopyFiles.bat';
system('cmd /c ' . $script); echo " <br>";
break;

Answer

The click event here is on the form:

<form action='Admin.php' enctype='multipart/form-data' method='post' onclick="myFunction()">

So it's going to fire that event when you click anything in the form. I suspect you want it in the onsubmit event instead?:

<form action='Admin.php' enctype='multipart/form-data' method='post' onsubmit="myFunction()">

Additionally, you have to actually cancel the form post following the confirm() response. First, add a return to the function call:

<form action='Admin.php' enctype='multipart/form-data' method='post' onsubmit="return myFunction()">

Then you'll also want to use a combination of "preventing default" and "returning false". Something like this:

function myFunction(e)
{
    e.preventDefault(); // here
    var x;
    var response = confirm("Copy all files?");
    if (response == true)
    {
        x = "You pressed OK!";
    }
    else
    {
        x = "You pressed Cancel!";
    }
    document.getElementById("demo").innerHTML = x;
    return response; // and here
}

So if the confirm() response is true, the function returns true and the form continues to submit. Else, the function returns false and the form doesn't submit.

Note that when the form submits, that update to the demo element will be gone because the page will refresh.