Reid W
Reid W

Reputation: 43

jquery -- how to set one radio button based on another getting clicked

Let's say I have a form that includes this:

<input type='radio' name='o37_field1' value='aaa'>aaa
<input type='radio' name='o37_field1' value='bbb'>bbb

<input type='radio' name='o44_field1' value='aaa'>abcdef
<input type='radio' name='o44_field1' value='bbb'>baksdf

<input type='radio' name='o58_field1' value='aaa'>wisdof
<input type='radio' name='o58_field1' value='bbb'>safhwr

Here's what I need to do with jquery but am having trouble:

If "aaa" is clicked on with in one of the sets, also set/check "aaa" for the other ones, and do the same for any other radio buttons that have "field1" as part of the name and "aaa" as the value.

Ditto for bbb

Any ideas?

Upvotes: 2

Views: 2519

Answers (3)

Steffan
Steffan

Reputation: 719

This will set all radios with a value of "aaa" when one is checked:

$(document).ready(function() {
   $(':radio[value=aaa]').change(function(){
       $(':radio[value=aaa]').prop('checked',true);
   });
});

The more robust solution like selecting all "like" values when one is clicked:

$(document).ready(function() {
    $(':radio').change(function(){       
       $(':radio[name$='field1'][value='+$(this).val()+']').prop('checked',true);
   });
});

Upvotes: 3

PSL
PSL

Reputation: 123739

Here you go. http://jsfiddle.net/5p8KN/ with endswith attribute selector to select field1.

$("input[type='radio']").click(function(){
$("input[type='radio'][name$='field1'][value='" + $(this).val() + "']").prop('checked',true);
});

if you want to look for contains attribute selector for field1 match then you can use input[name*='field1']

Upvotes: 1

PSR
PSR

Reputation: 40318

apply same class to all aaa radio buttons

then in click event use

$("input[type='radio']").click(function(){
  $(":radio[value="+$(this).val()+"]")).each(function(index,value){     
    $(this).attr('checked',true); or   $(this).attr('checked','checked');
   });
});

Upvotes: 0

Related Questions