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
?
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.
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.
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.
由于元素的ID是唯一的,因此$('#qty')。val()就足够了。
qty = $('#qty').val();
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.