Making my combo boxes independent in PHP and JQuery Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Making my combo boxes independent in PHP and JQuery without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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?

enter image description here

Answer

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);
            } 
        });

    });
});
We are here to answer your question about Making my combo boxes independent in PHP and JQuery - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji