Dropdown with Jquery/Ajax only sends data in the first record

Asked

Viewed 225 times

2

I am applying a dynamically dropdown to each item of a returned list in PHP. When selecting any of the dropdown items, this value is sent to an Update.php file, via Jquery and Ajax.

The Dropdown:

//Aqui tenho um while em PHP para criar um Dropdown para cada registro no Banco de dados
<select id="tipoSel">
   <option value="">Selecione o tipo:</option>
   <option value="Cívil">Cívil</option>
   <option value="Criminal">Criminal</option>
   <option value="Trabalhista">Trabalhista</option>
   <option value="Família">Família</option>
   <option value="Comercial">Comercial</option>
   <option value="Administrativo">Administrativo</option>
 </select>
 <input type="hidden" name="id" value="<?php echo $p->current()->id;?>" />

The Jquery:

$(document).ready(function(){
        $(function() {
            $("#tipoSel").bind("change", function(event) {
                var $this = $( this );

                var tipo = $this.val();
                var id = $this.next('input').val();

                $.ajax({
                    type: "POST", 
                    url: "Update.php",
                    data: 'tipo='+tipo+'&id='+id,
                    success: function(data) {
                        alert(tipo+' : '+id);
                    }
                });
            });

        });
    });

However, despite having multiple records, and all showing their respective Dropdown, the Jquery function only works for the first record of the page! The rest of them don’t even show the Alert...

What should be wrong? How to solve?

1 answer

4


Are all Dropdowns created with the id of tipoSel? The id of an element must be unique in the.

would use a class, creating a dropdown like this:

<select class="tipoSel">
   <option value="">Selecione o tipo:</option>
   <option value="Cívil">Cívil</option>
   <option value="Criminal">Criminal</option>
   <option value="Trabalhista">Trabalhista</option>
   <option value="Família">Família</option>
   <option value="Comercial">Comercial</option>
   <option value="Administrativo">Administrativo</option>
 </select>
 <input type="hidden" name="id" value="<?php echo $p->current()->id;?>" />

And then in your jQuery, select them like this:

$('.tipoSel').on( ... );
  • That’s exactly it! I hadn’t even paid attention... Thanks!

  • I’m glad it worked out :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.