How to concatenate an input name with a jQuery variable?

Asked

Viewed 9,617 times

3

I own a table that contains a button that adds a row to the table each time I click on it. The created line has 4 inputs, one of these inputs has an auto-Suggest / auto-complete function that searches for information in the database and returns this information to the other 3 input fields. As the image below

Tabela criada

Code:

<script>
 $(function(){
 var cnt = 0;
 var quantidadedisponivel;     

 $("#adicionar_item").click(function(){

    $('#tabela_publicacoes tr').last().after('<tr><td>#'+cnt+'</td><td><input type="hidden" name="titulopublicacao'+cnt+'" id="titulopublicacao'+cnt+'" style="width: 600px;"></td><td><input class="form-control" name="cod_publicacao'+cnt+'" type="text" disabled="disabled"></td><td><input class="form-control" disabled="disabled" name="valorunitario'+cnt+'" type="text" value=""></td><td><input class="form-control" name="quantidadedisponivel'+cnt+'" id="quantidadedisponivel'+cnt+'" type="text" disabled="disabled" value=""></td></tr>');        

     $('#titulopublicacao'+cnt).select2({
        placeholder: "Digite o título da Publicacao",
        ajax: {         
            url: 'autosuggest_busca_publicacao.php',
            dataType: 'json',
            quietMillis: 50,
            data: function (term) {
                return {
                    term: term
                };
            },
            results: function (data) {
                var results = [];                   
                $.each(data, function(index, item){
                    results.push({                          
                        text: item.titulopublicacao + " - Número: " + item.numero + " - Ano: " + item.ano,
                        id: item.cod_publicacao,
                        quantidadedisponivel: item.quantidadedisponivel                         
                    });                     
                });
                return {results: results};
            }
        },
    }); 

$('#titulopublicacao'+cnt).change(function() {  
        var selections = ( JSON.stringify($('#titulopublicacao'+cnt).select2('data')) );
        //console.log('Selected IDs: ' + ids);
        console.log('Selected options: ' + selections);
        //$('#selectedIDs').text(ids);          
       $("input[name='quantidadedisponivel"+cnt+"']").val(selections);
    });

cnt++;

$("#anc_rem").click(function(){
    if($('#tabela_publicacoes tr').size()>1){
        $('#tabela_publicacoes tr:last-child').remove();
    }else{
        alert('Erro, não foi possível remover');
    }
 });            
});
</script>

Part HTML:

<table id="tabela_publicacoes" class="table table-hover">
<thead>
   <tr> 
         <th>Item</th>
         <th>Título</th>
         <th>Código</th>
         <th>Valor Unitário</th>
         <th>Quantidade Disponível</th>
   </tr>
</thead>
<tbody>
</tbody>
</table>

<a href="javascript:void(0);" id="adicionar_item"><button class="btn btn-md btn-success btn-next">Adicionar Item</button></a>
<a href="javascript:void(0);" id="anc_rem"><button class="btn btn-md btn-danger btn-next">Remover Item</button></a>

My problem is that I cannot return the values to the 3 inputs. The statement $("input[name='quantidadedisponivel"+cnt+"']") with the +cnt+ concatenated gives problem, I am stating wrong?

  • I suggest changing the code strategy. Using each tr and go looking for the .parent() each .change(). If you also put the HTML of the part you have in the image I can respond with a suggestion

  • Thanks Sergio, follow the edited html part

  • What error does the console make? And, make a console.log(cnt); before $('#titulopublicacao'+cnt) and tell me the return.

  • William, thanks for your help. The return of the log: Uncaught Typeerror: Converting circular Structure to JSON

1 answer

3


Here is an idea:

Remove all this function $('#titulopublicacao'+cnt).change(function() {

Instead create a separate function like this:

function change(el) {
    var data = $(el.target).select2('data');
    var quantidade = data.quantidadedisponivel;
    var input = $(el.target).closest('tr').find('input').last().val(quantidade);
}

This function can now be called when your select receives a value change. Note that I changed a little what you had. I don’t understand why I had the stringify...

For that you have to add an Event Handler to select so:

$("#adicionar_item").click(function () {
    // etc

    $('#titulopublicacao' + cnt).select2({ // aqui começa o select2...
        placeholder: "Digite o título da Publicacao",
        // ect...

    }).on("change", change); // aqui no final junte isto

This event has the element changed inside and you can use it. Do not copy the ajax part of the example below, I switched to make the example.

Example: http://jsfiddle.net/JkV5q/

  • Thank you Sérgio, I’ll try it here !!! It was really worth it =)!

Browser other questions tagged

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