Reputation: 10696
Please see demo here: http://jsfiddle.net/9pR87/28/
I am creating some extra rows (invoice element), but when I want to use get the value in dynamically created input, but the input value is always undefined
. Why?
Why jQuery can not find value of dynamically created input?
Upvotes: 2
Views: 11112
Reputation: 87073
I think this is enough for what you want:
$('#GetValue').click(function() {
var i = $('table tbody tr').length-1; // subtract 1 for correct indexing
alert($('#ItemPrice-' + i).val());
// OR
alert( $('[id^=ItemPrice]:last').val() );
});
The problem is:
tableRow += '<td><input type="text" name="ItemPrice[]" id="ItemPrice-' + i + ' "
^--- an space
placeholder="Item Price"></td>';
tableRow += '<td><input type="text" name="NumberOfItems[]" id="NumberOfItems-' + i + ' "
^-- an space
placeholder="Number Of Items"></td>';
Here is update and working code
Upvotes: 6
Reputation: 53311
$('#GetValue').click(function() {
var i = $('table tbody tr').length; // this line is the issue
alert($('#ItemPrice-' + i).val());
});
I've copied the function in your code which is giving you the issue. The line I've highlighted should be this:
var i = $('table tbody tr').length-1;
This is because arrays in Javascript are 0-indexed, meaning they start counting upwards from zero. This means that if you want to get the last element of the array, you need to find the length of the array and subtract one, as I've demonstrated.
This line:
alert($('#ItemPrice-' + i).val());
actually returns an array, which starts counting at 0. That's why getting the element at position array.length
returns undefined.
Here's a working demo as proof.
Upvotes: 2