Reputation: 6355
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 .");
}
}
});
});
Upvotes: 2
Views: 2974
Reputation: 148
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();
}
}
});
Upvotes: 0
Reputation: 4076
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
}
}
});
Upvotes: 1
Reputation: 2537
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.
Upvotes: 4
Reputation: 4964
$('#test-with-prop').click(function () {
if ($('#mycheckbox').is(":checked")) {
return true;
}
else {
alert("Checkbox is not selected");
return false;
}
});
Upvotes: 1