简体   繁体   中英

jQuery How to Use radio button to control radio buttons

 $(function() { $("#aa").click(function() { $("#aa2").attr("checked", true); }); $("#bb").click(function() { $("#bb2").attr("checked", true); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='radio' name='a' id='aa'/>aa <input type='radio' name='a' id='bb'/>bb <br> <input type='radio' name='b' id='aa2'/>aa2 <input type='radio' name='b' id='bb2/'>bb2 

When I click aa, aa2 checked, click bb, bb2 cheked. However, then click aa, bb2 remains checked, and aa2 is not checked

You likely need to use the .prop() method instead of the .attr() method.

When using .attr() , you are setting an attribute. When the attribute is set, the property will be set. In your case, if the attribute has already been set, it will not change the property again, therefore you should just change the property using .prop() to begin with.

As a side note, I'd suggest listening to the change event of the radio elements rather than the click event.

Example Here

$("#aa").on('change', function () {
    $("#aa2").prop("checked", "checked");
});
$("#bb").on('change', function () {
    $("#bb2").prop("checked", "checked");
});

See .prop() vs .attr() .

This should work for you

 $(function() { $("input[name=a]").change(function() { $("input[name=b]").removeAttr('checked'); $("input[name=b]").filter('[value='+$(this).val()+']').attr('checked', true); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='radio' name='a' value="1" />aa <input type='radio' name='a' value="2" />bb <br> <input type='radio' name='b' value="1" />aa2 <input type='radio' name='b' value="2" />bb2 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM