10

jQuery: Choose an appropriate radio button

 3 years ago
source link: https://www.codesd.com/item/jquery-choose-an-appropriate-radio-button.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

jQuery: Choose an appropriate radio button

advertisements

Here is the html code:

<div id="id1">
<input type="radio" name="sex" value="Male">Male</input>
<input type="radio" name="sex" value="Female">Female</input>
<input type="radio" name="sex" value="Unknown">Unknown</input>
</div>
<div id="id2">
<input type="radio" name="sex" value="Male">Male</input>
<input type="radio" name="sex" value="Female">Female</input>
<input type="radio" name="sex" value="Unknown">Unknown</input>
</div>

How to make the same radio button to be selected anytime for both id1 and id2 using jQuery?

Example: once you select Female from id1, Female from id2 is chosen automatically.

Example: once you select Male from id2, Male from id1 is chosen automatically.

I need it using jQuery.


You can use this code however you need to change the name of the input elements in your second div, otherwise they'll be part of the same group.

$('#id1 input,#id2 input').click(function () {
    $('#id1 input').eq($(this).index()).prop('checked', true);
    $('#id2 input').eq($(this).index()).prop('checked', true);
});

jsFiddle example


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK