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

3 Answers 3

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/

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Great! wrapping it in .ready worked, what's the benefit of using .prop over .is?
it has the same function
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.