1

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.")        
    }
 });
NipBoss
  • 153
  • 1
  • 2
  • 13
  • 3
    Possible duplicate of [jQuery if checkbox is checked](http://stackoverflow.com/questions/7960208/jquery-if-checkbox-is-checked) – Imesha Sudasingha Feb 07 '17 at 01:49
  • Possible duplicate of [Check/Uncheck checkbox with javascript?](http://stackoverflow.com/questions/8206565/check-uncheck-checkbox-with-javascript) – Atticus Feb 07 '17 at 01:51

3 Answers3

2

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/

timleathart
  • 520
  • 1
  • 5
  • 20
1

wrap it in $(document).ready(function(){}); and use .prop()

$(document).ready(function(){
  $('#submit').on('click', function() {
     if($('#terms').prop('checked')==true) {
    }
    else {
     alert("To proceed you must accept the terms.")        
    }
   });
});
pryxen
  • 381
  • 2
  • 22
0

The reason your JSFiddle doesn't work is that you need to wait until the document is loaded before attaching event handlers. Otherwise, jQuery is looking for the submit button before it even exists.

To make sure the button has loaded, use $(document).ready():

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

Note that you already had an extra closing brace and bracket (which was a syntax error), which now closes the $(document).ready function.

Jordan
  • 2,281
  • 1
  • 17
  • 24