001221 001221 - 2 months ago 12
HTML Question

jquery do not submit form until checkbox is ticked

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 .");
}
}
});
});

Answer

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.