Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating a radio button is checked with jQuery

On my form I havea 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 check that one of them is checked. What's the best way to go about this? I was thinking of looping through them all and making a flag to set if one of them is checked, and then check the flag after the loop and if it's false throw an error.

Any help is appreciated, cheers.

like image 413
Will Avatar asked Sep 23 '10 15:09

Will


People also ask

How check radio button is empty or not in jQuery?

Try the code below. radio = $('input:radio[name=priority]'). val(); EDIT: Okay, this should do it for radio button validation.

How can I change checked radio button in jQuery?

You just need to some step to done set radio button checked jquery by id. var value = 2; $("input[name=type][value=" + value + "]"). prop('checked', true);


2 Answers

You can use the length and equal attribute selector with :checked filter selector like this:

if ($("input[name='fileType']:checked").length > 0){
  // one ore more checkboxes are checked
}
else{
 // no checkboxes are checked
}
like image 118
Sarfraz Avatar answered Nov 15 '22 11:11

Sarfraz


demo

http://jsfiddle.net/Vq2jB/2/

var isChecked = jQuery("input[name=fileType]:checked").val();
like image 38
Praveen Prasad Avatar answered Nov 15 '22 10:11

Praveen Prasad