Iladarsda
Iladarsda

Reputation: 10696

jQuery - get a value from dynamically created input

Please see demo here: http://jsfiddle.net/9pR87/28/

  1. Add Input - adds new row with new input
  2. Get Value - is getting value of last added input

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

Answers (2)

thecodeparadox
thecodeparadox

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() );
});

Demo

According to comment with jsfiddle

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

Elliot Bonneville
Elliot Bonneville

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

Related Questions