Posted By

jurajhilje on 04/28/11


Tagged

jquery radio validation


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Some0ne


jQuery radio input validation


 / Published in: jQuery
 

  1. // Javascript
  2.  
  3. var $form = $('#form-id'),
  4. error;
  5.  
  6. $form.submit(function()
  7. {
  8. error = 0;
  9.  
  10. // check if radio groups are selected
  11. $form.find('input:radio').each(function()
  12. {
  13. var radioGroupName = $(this).attr('name'),
  14. $radioGroup = $form.find('input:radio[name='+radioGroupName+']');
  15.  
  16. // check only if radio group exists
  17. if( $radioGroup.size() )
  18. {
  19. if( !$radioGroup.is(':checked') ) error = 1;
  20. }
  21. });
  22.  
  23. // handle error
  24. if(error)
  25. {
  26. // output your error message
  27. return false;
  28. }
  29. });
  30.  
  31.  
  32. // HTML
  33.  
  34. <form id="form-id" action="" method="post">
  35. <input type="radio" name="my_radio_group" value="1" />
  36. <input type="radio" name="my_radio_group" value="2" />
  37. <input type="radio" name="my_radio_group" value="3" />
  38. <input type="submit" value="Submit" />
  39. </form>

Report this snippet  

You need to login to post a comment.