Posted By

chrisaiv on 09/20/08


Tagged

jquery validation


Versions (?)

Who likes this?

9 people have marked this snippet as a favorite

sulfurito
luman
elgermano
xuanyan
Hollow
loric
cfleschhut
seanpowell
nwpratt


JQuery: Ensure that at least one checkbox is selected


 / Published in: JavaScript
 

Ok so here's the scenario, Suppose you have some sort of form with a couple of checkboxes and you want the user to select at least one before submitting, rather than write a bunch of iteration code, JQuery offers a really easy way to do it.

  1. function setHiddenAction(element) {
  2. var okToSubmit = false;
  3. //A. Make sure that the user selects at least one item before they Request an Action
  4. if( $("input:checkbox:checked").length > 0 ) okToSubmit = true;
  5. //B. Set the Hidden Value to the Users Requested Action
  6. $("#action").attr("value", element.value)
  7. //C. Either Submit or give an Error Message
  8. if( okToSubmit ) {
  9. $("form").submit();
  10. } else {
  11. alert( "Please select at least one item" );
  12. }
  13. }
  14.  
  15. setHiddenAction("email");

Report this snippet  

You need to login to post a comment.