Confirm the box does not work when I get a value from a php and javascript form

advertisements

This seems really odd to me, but my popup confirm box will work when i just call the function, but as soon as i try to get a value from a form in my php code, the popup box doesnt work at all!

javascipt:

function ConfirmBox(){
    cert = cValForm.elements["cVal"].value;
    answer = confirm("Are you sure you want to delete " + cert + " and all of its courses?");
     if (answer){
         alert("Entry Deleted");
     }
     else{
         alert("No action taken");
     }
}

PHP:

echo "<form name='cValForm'>";
echo "<input type='hidden' name='cVal' value='TEST' /> ";
echo "<input type='button' onclick='ConfirmBox()' value='Delete'/>";
echo "</form>";

As soon as i comment out the line:

cert = cValForm.elements["cVal"].value;

As well as getting rid of the cert value in the string, the popup works completely fine. Am i getting the value from the form wrong? Or am i completely missing something here? Thanks!


I think you script breaks, because it is not able to find the value of the cVal field.

Change your HTML to use Ids as well as names:

<form name='cValForm'>
  <input type='hidden' id="cVal" name='cVal' value='TEST' />
  <input type='button' onclick='ConfirmBox()' value='Delete'/>
</form>

And then check in JavaScript first, if the element was selected at all:

function ConfirmBox(){
    var certField = document.getElementById( 'cVal' );
    var cert = certField ? certField.value : '';
    var answer = confirm("Are you sure you want to delete " + cert + " and all of its courses?");
     if (answer){
         alert("Entry Deleted");
     }
     else{
         alert("No action taken");
     }
}

Besides, you should add the keyword var to all you variable declarations to limit the scope of these vars to the local function. In your case those variables would have been global, which may have some side-effects.