0

I want to check if there's at least one checkbox that checked in a form after the submit button is clicked, if no, the the user should get message and the form SHOULDN'T be submit, so I wrote this code:

 jQuery(document).ready(function ($) { $('#price_quote_create_invoice').click(function () { $('.price-quotes-table input[type="checkbox"]').each(function () { if ( $(this).is(':checked') ){ $('#post').submit(); return false; } else { alert("You didn't chose any checkbox!"); return false; } }) ; }); }); 

However, after I press ok on the alert box, the form does submit.

Any idea why this is happening?

3 Answers 3

1

Your code is almost right.

You return false on a click event but what you really want to do is to stop the submit event.

Change like this.

$('#yourFormId').submit(function(){ if (!$(this).find('input[type="checkbox"]:checked').length) { alert("You didn't chose any checkbox!"); return false; } }); 
Sign up to request clarification or add additional context in comments.

2 Comments

So. Submit form -> Prevent submitting (e.preventDefault();) -> Check if chekked or not and show alert. You do realise that the form will never be send now, right?
Yep you're right. I just coded those lines too quickly. My bad. Thanks
0
 alert('You didn't chose any checkbox!'); 

You have an additional comma in your alert..

Comments

0

You can use event.preventDefault() to do this. event is the first argument of your click function. Reference

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.