Popular inputs with jquery and insert table rows at the same time

1

I have an input that when you insert the enrollment (ID) of a person, the rest of the table populate dynamically, and another row of the table is automatically inserted, which would work the same way, the enrollment and the rest of the row complete again and so on. But only the first line works, the others do not, and I have no idea how to solve it. Here is the code:

<script type="text/javascript">
    $(document).ready(function(){
        var x = 0;
        $(document).on('blur', 'input[name="matBusca['+ x +']"]' ,function(){
            var y = x + 1;
            $('#listas').append('\
            <tr><td><input type="text" name="matBusca['+ y +']"></td>\
            <td><input type="text" name="nomeBusca['+ y +']"></td>\
            <td><input type="text" name="cargoBusca['+ y +']"></td>\
            <td><input type="text" name="clpdBusca['+ y +']"></td>\
            ');
            $("input[name='matBusca["+ y +"]']").focus();
            var $nome = $("input[name='nomeBusca["+ x +"]']");
            var $cargo = $("input[name='cargoBusca["+ x +"]']");
            var $clpd = $("input[name='clpdBusca["+ x +"]']");
            $nome.val('Carregando...');
            $cargo.val('Carregando...');
            $clpd.val('Carregando...');
            $.getJSON(
                'function.php',
                { matBusca: $( this ).val() },
                function( json ){
                    $nome.val( json.nome );
                    $cargo.val( json.cargo );
                    $clpd.val( json.clpd );
                }
            );
            x++;
        });
    });
</script>
    
asked by anonymous 01.04.2017 / 06:22

1 answer

0

The problem is that only input[name="matBusca[0]"] will react to blur because when the $(document).on('blur', 'input[name="matBusca['+ x +']"]' ,function(){ line is read x has a value of zero.

You have to make this delegator input[name="matBusca['+ x +']"] accept the others as well.

The solution is to use ^= that tells jQuery to use selectors starting with . In your case it could be input[name^="matBusca"] .

Example:

$(document).on('blur', 'input[name^="foo"]', function() {
  console.log(this.name);
});
input {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" name="foo[0]">
<input type="text" name="foo[1]">
<input type="text" name="foo[2]">
<input type="text" name="foo[3]">
    
01.04.2017 / 10:20