jQuery radio input validation


/ Published in: jQuery
Save to your folder(s)



Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.