0

I'm trying to get the ID of newly added input field on a table row.

I add the input field as so...

    $('#addmore').click(function(){

    // Get last id 
    var lastname_id = $('.tr_input input[type=text]:nth-child(1)').last().attr('id');
    var split_id = lastname_id.split('_');

    // New index
    var index = Number(split_id[1]) + 1;

    // Create row with input elements
    var html = '<tr><td><input class="form-control" type="number" id="qty_'+index+'" name="qty['+index+']" min="0.01" step="0.01" max="2500" placeholder="0" required /></td><td><input class="form-control pnumber" type="text" id="pnumber_'+index+'" name="pnumber['+index+']" placeholder="Numero del Producto" required /><div style="z-index: 99;" id="suggesstion-box"></div></td><td><input class="form-control" type="number" id="price_'+index+'" name="price['+index+']" min="0.01" step="0.01" max="2500" placeholder="0" required /></td><td><input class="form-control" type="number" id="total_'+index+'" name="total['+index+']" min="0.01" step="0.01" max="2500" placeholder="0" disabled /><td valign="top"><input type="button" name="delete" id="delete_'+index+'" class="btn bg-danger" value="Delete" /></td></tr>';

    // Append data
    $('#MyTable> tbody:last-child').after(html);
});

This is how I try to get the ID

$(document).ready(function(){
    $('.pnumber').keyup(function(){
        var id = $(this).attr("id");
        console.log(id);
    });
});

This works fine with the input field that is on the original HTML, but not with the ones added on with the JQuery function.

Dante
  • 1
  • You need to use event delegation for elements created after you attach the event. `$(document).on("keyup", ".pnumber", function(){` – freedomn-m Dec 27 '21 at 18:36
  • Also note: you don't need an html element ID. If you think you do, think again. *Maybe* you need a data attribute, but not an html element ID. – freedomn-m Dec 27 '21 at 18:54

1 Answers1

0

You must use data-id attribute in html tag. For example

<input type="text" data-id="attr-value"/>
  • What effect are you expecting this to have? Changing this alone will make absolutely no difference to the problem in the question. – Rory McCrossan Dec 27 '21 at 18:47
  • Generally for "custom" attributes, these days you should add a `data-` prefix, eg `data-user-id` - but for `id` if it is a *true* html ID, (which it's not in this case) then it should still be `id=` – freedomn-m Dec 27 '21 at 18:53