简体   繁体   中英

Javascript form validation onSubmit not triggering

please can someone help. this form validation is not triggering.. It's really frustrating me. I'm a PHP developer rather than JS so i'm struggling a bit with this even though it's clearly something very simple. I'm just trying to validate the form based on the delete box being ticked.

Nothing appears when I click submit. It just submits the form so it must be returning true.

function deleteVal(chk) {

    var chk;

    // If the checkbox has been set to delete
    if (chk.checked == "delete") {

        var ok=confirm("You are about to delete the selected images below.\nAre you sure you want to do this?");

        if (ok) {

            // Submit
            return true;

        } else {

            // Don't submit
            return false;

        }

    }

    // Delete box was not ticked so return true and submit form
    return true;

}

</script>

<form action="" method="POST" onSubmit="return deleteVal(delete)">
  <label>Delete images?</label><input type="checkbox" name="delete" value="delete" />
  <input type="submit" name="submit" value="Submit" />
</form>

You need to get the checked value properly like so and see if it is true or false.

var chk = document.getElementById('delete');

// If the checkbox is checked
if (chk.checked == true) {

Then you do not need to pass a variable to the function, however, you do need to give you checkbox an id.

<form action="" method="POST" onSubmit="return deleteVal();">
  <input type="checkbox" name="delete" id="delete"/>
  <input type="submit" name="submit" value="Submit" />
</form>

Tested code - http://pastebin.com/FdWdeSCN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM