Dropdown with JQuery / Ajax only sends data in first record

1

I'm dynamically dropping a dropdown for each item in a list returned 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;?>" />

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 are displaying their respective Dropdown, the JQuery function only works for the first record of the page! The others do not even display the alert ...

What must be wrong? How to solve?

    
asked by anonymous 19.07.2015 / 00:58

1 answer

3

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

I 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( ... );
    
19.07.2015 / 01:06