NipBoss NipBoss - 4 years ago 92
jQuery Question

How to verify if checkbox is checked before proceeding?

how do you check if a checkbox is checked when clicking submit?
I want it to show an alert when the box is unchecked.

http://jsfiddle.net/tjE24/42/

$('#submit').on('click', function() {
if($('#terms').is(':checked')) {
}
else {
alert("To proceed you must accept the terms.")
}
});
});

Answer Source

It looks like what you want to do is stop the form from submitting if the checkbox is not checked. Your code will still submit the form, no matter what the outcome of your function is. What you need to do is put the inputs into a <form> tag, and add a handler for the onsubmit event, which will cancel the form submission.

HTML:

<form onsubmit="return check_checkbox()">
    <input type="checkbox" id="terms" unchecked/>Terms
    <br /><br />
    <button id="submit">
        continue
    </button>
</form>

Javascript:

function check_checkbox() 
{  
  if($('#terms').is(':checked')) {
    return true;
  } else {
    alert("To proceed you must accept the terms.");
    return false;
  }
}

http://jsfiddle.net/tjE24/47/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download