hohner
hohner

Reputation: 11588

jQuery problem with multiple radio selects

I'm trying to validate a form that contains several different radio buttons. A few radio buttons in the form have the same classname 'video_type'.

In the jQuery validation script, after the form is submitted I want to check if any of the radio buttons with the classname 'video_type' have been selected. If the user has selected at least one radio button with the classname 'video_type' and the value as 1, it should return true. Otherwise it should return false.

At the moment I'm using this:

HTML:

<input type="radio" name="video_option_1" class="video_option" value="1">Yes
<input type="radio" name="video_option_1" class="video_option" value="0">No

<input type="radio" name="video_option_2" class="video_option" value="1">Yes
<input type="radio" name="video_option_2" class="video_option" value="0">No

jQuery:

$("#completeOrderForm").submit(function(){
 if($(".video_type").val() == 0){
   $("#showerrors").show().html("Please select a video type.");
   return false;
 } 
});

But I realise it's incorrect. What do I need to do?

Upvotes: 0

Views: 85

Answers (1)

Bj&#246;rn
Bj&#246;rn

Reputation: 2648

This should work:

if ($(".video_option[value='1']:checked").length == 0) {
   $("#showerrors").show().html("Please select a video type.");
   return false;
 } 

Basically you're selecting every element with the class .video_option that have the value 1 ([value='1']) and are checked (using the :checked selector). It then counts the amount of elements selected, if the result is 0 no radio's are checked.

Fiddle: http://jsfiddle.net/bjorn/UwufF/6/

EDIT You talk about radio buttons with the classname video_type yet the code shows video_option, I went by the code when making the example.

Upvotes: 1

Related Questions