Rocksteady
Rocksteady

Reputation: 281

Multiple Select tags with dynamic options

I have a site with multiple select tags that comes in pair. enter image description here

So when I choose a team in select tag 1, i want all players from that team to appear in the closest select tag (2) Player. I have done all the player fetching and i have my result ready. But when I update the select tag using javascript i face a problem, either all player-tags update with the same value or none does. SO! My problem is that I want to update only the next (.player) select tag and not every .player tag?

enter image description here

HERE IS A DEMO

<div>
    <i>1</i>
    <select class="country">
        <option selected="selected">Team</option>
        <option value="England">England</option>
        <option value="Italy">Italy</option> 
    </select> 
</div> 
<div>
    <i>2</i>
    <select class="player">
           <option selected="selected">Player</option>
    </select>
</div>
<div>
    <i>1</i>
    <select class="country">
        <option selected="selected">Team</option>
        <option value="England">England</option>
        <option value="Italy">Italy</option>
    </select>
</div>
<div>
    <i>2</i>
    <select class="player">
        <option selected="selected">Player</option>
    </select>
</div>
$(document).ready(function() {
    $(".country").change(function() {
        $(this).next(".player").html("<option value='test'>test</option>");
    });
});

Upvotes: 1

Views: 949

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because .player is not a sibling of .country. You need to find the closest parent div, then go to the next div and find the .player in there. Try this:

$(".country").change(function() {
    $(this).closest('div').next('div').find('.player').html("<option value='test'>test</option>");
});

Updated fiddle

Upvotes: 1

Related Questions