Taly Chan
Taly Chan

Reputation: 1

JQuery - Autocomplete and dynamic inputs

My page creates multiple rows with three text inputs in each. The functions to add and remove fields works correctly.

I need that after the user typing in the code, search the database and change the value of the field name.

The problem is that it only works on the first line, and does not work for each field created. the customer can add as many lines you want, after sending it to a php file that will create a csv file with this information.

html

<div id="campos">
    <table border="0" cellpadding="2" cellspacing="4">
        <tr>
            <td>
                Excluir
            </td>
            <td align="center">
                Codigo no Bag:
            </td>
            <td>
                Nome Comum:
            </td>
            <td>
                Quantidade de registros:
            </td>
        </tr>
        <tr class="linhas">
            <td>
                <a href="#" class="removerCampo" title="Remover linha"><img src="../imagens/w_close.gif" width="11" height="11"></a>
            </td>
            <td>
                <input name="index_linha[]" type="hidden" value="1"> <input type="text" name="cod[]" id="cod" onblur="Busca_nome_acesso(this.value)">
            </td>
            <td>
                <input type="text" name="nome_acesso[]">
            </td>
            <td>
                <input name="qtd[]" type="text" size="5" maxlength="5">
            </td>
            <td></td>
        </tr>
        <tr>
            <td colspan="5" align="right">
                <label><a href="#" class="adicionarCampo" title="Adicionar item"><img src="../imagens/IconeMaisQuadrado.gif">Adicionar campo</a></label>
            </td>
        </tr>
        <tr>
            <td align="center" colspan="4">
                <span>&nbsp;</span> <input type="submit" id="btn-cadastrar" value="Cadastrar">
            </td>
        </tr>
    </table>
</div>

</div></form>

</div>

Script jquery

$(function () {
    function removeCampo() {
        $(".removerCampo").unbind("click");
        $(".removerCampo").bind("click", function () {
            if ($("tr.linhas").length > 1) {
                $(this).parent().parent().remove();
            }
        });
    }


    $(".adicionarCampo").click(function () {
        var num_linhas = $("tr.linhas").length;
        if ($("tr.linhas").length < 10) {
            novoCampo = $("tr.linhas:first").clone();
            novoCampo.find("input").val("");
            novoCampo.insertAfter("tr.linhas:last");
            novoCampo.find('input:text:first').focus();
            novoCampo.find('input:hidden:first').val(num_linhas);
            removeCampo();
        }
    });

    //Function to search the database
    function Busca_nome_acesso(valor) {

        $.getJSON('busca_nome.php?search=', {
            valor: valor,
            ajax: 'true'
        }, function (j) {
            var resp = '';
            for (var i = 0; i < j.length; i++)
            resp += j[i].nome_comum_1;
            //return the answer here but dont know how
        });
    }

I also tried using the delegate,live and on methods.

$("#tr.linhas").delegate("blur", $("#cod")function () {

    $.getJSON('busca_nome.php?search=', {
        valor: $(this).val(),
        ajax: 'true'
    }, function (j) {
        var resp = '';
        for (var i = 0; i < j.length; i++)
        resp += j[i].nome_comum_1;
        //Just to test, I do not know how to return the correct location
        alert(resp);
    });
})

Upvotes: 0

Views: 432

Answers (1)

Brandon Buck
Brandon Buck

Reputation: 7181

I'm not sure what you've tried but I've got a working fiddle here: http://jsfiddle.net/9ULgR/ that you can check out. Basically all that I did is change the id="cod" on the input to class="cod" because you cannot duplicate IDs in a document, it will always cause unexpected problems. After that I simply used jQuery's on event to register an event on non-dynamic parent (#campos) and delegated to the dynamic input (input.cod) and it works when you focus something other than the input it fires my alert with the text of the box.

I also removed the onblur attribute from the tag. I'm not sure if that was causing any problems but if you're going to use jQuery (or Javascript) to register events, don't also do that in HTML.

Here is the event handler I wrote:

$("#campos").on("blur", "input.cod", function() {
  alert("Make request for " + $(this).val()); 
});

Upvotes: 1

Related Questions