Question

Hi I've inserted some jquery in order to validate a checkbox on a certain form, I've made a simple example on my jsFIddle however the form still submits if the checkbox is not clicked, however the alert is still displayed.

How can i stop the submit taking place if the checkbox is not ticked? My code is below or view my jsFIddle

$(document).ready(function () {

var check;

$("#test-with-prop").on("click", function () {
    if ($("input[id=test]").is(":checked")) {
        check = $("#mycheckbox").prop("checked");
        if (!check) {
            alert("Please confirm that you have read and understood the charging agreement between yourself, and .");
        } 
    }
});
});
Was it helpful?

Solution

You should use the $.on('submit') as described here.

for example:

$(document).ready(function () {
    var $form = $('#form-id');
    var $checkbox = $('#mycheckbox');

    $form.on('submit', function(e) {
        if(!$checkbox.is(':checked')) {
            alert('Please confirm!');
            e.preventDefault();
        }
    });
});

Here is a working example.

OTHER TIPS

$('#test-with-prop').click(function () {
            if ($('#mycheckbox').is(":checked")) {
                return true;
            }
            else {
                alert("Checkbox is not selected");
                return false;
            }
        });

only add the e.preventDefault(); and cancel the submit:

 // Example 3 - With jQuery prop  
    $("#test-with-prop").on("click", function (e) {
        if ($("input[id=test]").is(":checked")) {
            check = $("#mycheckbox").prop("checked");
            if (!check) {
                alert("Please confirm");
                e.preventDefault(); // add this line
            } 
        }
    });

You could try this. And use a as Inputtype a Button instead of type="submit"....

$("#test-with-prop").on("click", function () {
        if ($("input[id=test]").is(":checked")) {
            check = $("#mycheckbox").prop("checked");
            if (!check) {
                alert("Please confirm that you have read and understood the charging agreement between ");
            } else{
                $("#form").submit();
            }
        }
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top