Reputation: 281
I'm having some trouble with populating combo boxes with database content depending on what the user chooses in another combobox. It works fine when I use one 'pair' of boxes. COUNTRY -> PLAYER. But when I add several COUNTRY->PLAYER on the same page, all my players get chosen by the first COUNTRY BOX. Here is a snap of my code, it is created from this webpage example:
<script type="text/javascript">
$(document).ready(function(){
$(".country").change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ajax-search.php",
data: dataString,
cache: false,
success: function(html){
$(".player").html(html);
console.log(id);
}
});
});
});
</script>
while ($row = mysql_fetch_array($result)) {
$counter++;
echo '<select class = "country" name="singleBetTeam[' . $counter . ']">';
echo "<option selected = 'selected'> COUNRTY</option>";
while ($row = mysql_fetch_array($result2)) {
$data = $row['team_name'];
echo '<option value="'.$data.'">'.$data.'</option>';
}
echo '</select><select name="singleBetStar[' . $counter . ']" class="player">';
echo '<option selected="selected"> PLAYER </option></select>';
}
The problem is that when I choose Germany in the first Combobox, then I get the German players all of the other combo boxes for player. This is depending on the fact that I check for class="player" in the javascript but I don't know how to create this connection?
Upvotes: 0
Views: 201
Reputation: 781004
You should only update the combobox following the one that the user changed, rather than all elements matching the player
class. You can use the context:
option to $.ajax
to pass the changed element to the callback.
$(document).ready(function() {
$(".country").change(function() {
var id=$(this).val();
$.ajax ({
type: "POST",
url: "ajax-search.php",
data: {id: id},
cache: false,
context: this;
success: function(html) {
$(this).next(".player").html(html);
console.log(id);
}
});
});
});
Upvotes: 1