Testing a switch using jQuery
In my form, I have a set of radio buttons. Here's the mark up:
<div class="optionHolder"> <p class="optionName">Format</p> <div class="option checked"> <input type="radio" name="fileType" value="avi" /> <img src="images/avi.png" alt="" /> <label>AVI</label> </div> <div class="option"> <input type="radio" name="fileType" value="mov" /> <img src="images/mov.png" alt="" /> <label>MOV</label> </div> <div class="option"> <input type="radio" name="fileType" value="mp4" /> <img src="images/mp4.png" alt="" /> <label>MP4</label> </div> <div class="option"> <input type="radio" name="fileType" value="mp3" /> <img src="images/mp3.png" alt="" /> <label>MP3</label> </div> </div> When the form is submitted, I want to verify that one of them is checked. What is the best way to do this? I thought about scrolling through all of them and making a flag to determine if one of them was checked, then check the flag after the loop and if it falsely gives an error.
Any help is appreciated.
Try the jQuery Validation plugin. It can do a lot for you and be very useful for many different forms. If you want to do this very simply:
if($("input[name=fileType]:checked").length > 0) { //Is Valid } Really old, I know. If the radio selection is not selected, it returns as "undefined", not "0". In my example, I declare a variable with the value of the switches. If the specified value is undefined, javascript returns false.
gender = $('input[name=gender]:checked').val(); if(typeof gender === 'undefined'){ alert('Do not move on'); $('input[name=gender]').css('box-shadow', '0 0 2px 0 red'); return false; }