Klapsius
Klapsius

Reputation: 3359

JQuery get value from dynamically created input by tr

I have dynamically created table with JQuery and i would like to get value of input elements:

$el.append('<tr data-id='+ data[i].id + ' data-token='+data[i].token + '><td>'+data[i].order+'</td>\n\
      <td><input name="qty" id="qty" type="number" value="'+data[i].qty+'" min="1"></td>\n\
   ......

With this code i can generate table(this is a fragment of code only). I know how to access into values of tr tag:

$('body').on('click', 'a.link', function(e) {
    e.preventDefault();

    var tr = $(this).closest('tr'),
        id = tr.data('id'), // we have the id
        token = tr.data('token'), // we have the token 
        qty = tr.data('qty'); <------------- this not working
 })

How to get value of qty?

Upvotes: 3

Views: 16238

Answers (5)

Pawan
Pawan

Reputation: 573

qty = tr.data('qty'); this means you want to access the data attribute, since you are not having any data attribute like "data-qty", you can't access it. So either make it a class or id.

Upvotes: 0

Rajshekar Reddy
Rajshekar Reddy

Reputation: 18987

Problem: You don't have a data-qty attribute in your tr. Also there is no data-qty at all in your table.

Solution: During your table creation you are assigning the data[i].qty to your input element as value. Hence you need to read the input value. Like below.

   qty = tr.find('#qty').val();

NOTE: Satpal provided a valid point. If at all you are building the tr in a loop then you are assigning the same id to all the input elements in the all the rows which is not recommended. Its better you remove the id attribute and just use the name attribute to select the element. like

tr.find('input[name="qty"]').val(); or tr.find('td:eq(1) input').val()

However if this is the case then Satpal gave the right answer.

Upvotes: 10

Satpal
Satpal

Reputation: 133403

You should use .find() in conjunction with Attribute Equals Selector [name=”value”].

qty = tr.find('[name=qty]').val();

As you are creating element dynamically with id="qty" it will create invalid HTML. Since identifiers must be unique.

Upvotes: 2

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

First the id should be unique in the same document so you could replace the id by class in :

<input name="qty" class="qty" type="number" value="'+data[i].qty+'" min="1">

Then if you want to get the input value you could use find and the class of the input then .val(), so it should be :

qty = tr.find('.qty').val();

Hope this helps.

Upvotes: 5

Sanjay Kumar N S
Sanjay Kumar N S

Reputation: 4739

Since the id of the element is unique, $('#qty').val() is enough.

qty = $('#qty').val();

Upvotes: 1

Related Questions