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

Asked

Viewed 213 times

1

I have an input that when inserted the matricula (identification) of a person, the rest of the table populates dynamically, and is automatically inserted another row of the table, which would work in the same way, insert the registration plate and the rest of the complete line again and so on. But only the first line works, the others do not, and I have no idea how to solve. Follow 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>

1 answer

0


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

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

The solution is to use ^= that tells jQuery to use selectors "begin 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>
<input type="text" name="foo[0]">
<input type="text" name="foo[1]">
<input type="text" name="foo[2]">
<input type="text" name="foo[3]">

  • I think you could clear your code a little bit more and look like this: https://jsfiddle.net/jxbbvsa4/

  • 1

    Sergio thanks a lot, it worked out here.

Browser other questions tagged

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