Reputation: 1552
I have a table which is auto-generated with data from the database and created using jquery. This is created using the following tr variable which is appended to the main tbody : Below is my code :
var list = " <tr id='order_no_tr'><td id='order_no_td" + item.documentno + "'>" + item.documentno + "</td><td>" + item.progressstatus + "</td><td>" + newDate + "</td>\n\
<td><button type='button' id='cnfrmd_rcvd" + item.c_order_id + "' class='btn btn-default btn-sm cnfrmd_rcvd" + item.c_order_id + "' >Confirm Received</button>\n\
<input type='hidden' name='order_no_txt' id='order_no_txt" + item.c_order_id + "' value='" + item.c_order_id + "' class='order_no_txt" + item.c_order_id + " btn btn-primary'/>\n\
</td></tr>";
$("#order_no_tbody").append(list);
$("#order_no_tr").on("click", ".cnfrmd_rcvd" + item.c_order_id, function() {
var order_no = this.value;
alert(order_no);
});
Now I want to get the value of the html input name called order_no_txt, I have tried accessing it through the following function but it fails :
$("#order_no_tr").on("click", ".cnfrmd_rcvd" + item.c_order_id, function() {
var order_no = this.value;
alert(order_no);
});
Please advise on how I can achieve this?
Upvotes: 0
Views: 1139
Reputation: 133403
Since the hidden element is sibling of button, you can use the relationship to traverse up to element using .next()
and fetch its value using .val()
method.
$("#order_no_tr").on("click", ".cnfrmd_rcvd" + item.c_order_id, function() {
var a = $(this).next(':hidden').val();
//Following can also be used
//$(this).closest('td').find(':hidden').val()
alert(a);
});
References
You should learn event delegation, for dynamically created elements.
As per comment The click only works for the first record and fails for the others., Identifiers must be unique. It seems you are reusing order_no_tr
as ID multiple time so that's the expected behaviour.
Change
$("#order_no_tr").on("click", ".cnfrmd_rcvd" + item.c_order_id, function() {
});
To
$(".cnfrmd_rcvd" + item.c_order_id).on("click", function() {
});
Upvotes: 1