Sujit
Sujit

Reputation: 790

get array value of dynamically created inputs by jquery

this is a simple code

<?php for($i=0; $i<5; $i++){ ?>
    <input type="text" id="modify_album_title_input" name="modify_album_title_input[]" value="" required=""/>
<?php } ?>

I can easily get the value by php in a form of array. But how to get the value by jquery? I have already used this...

alert($("input[name='modify_album_title_input']").val());

result is 'undefined' and this...

var input_array= $("input[name='modify_album_title_input[]']").val();
alert(input_array);

result only the first of the input, not an array. Any solution guys? thanks in advance...

Upvotes: 1

Views: 2152

Answers (3)

Matt Grande
Matt Grande

Reputation: 12157

A couple things I'm noticing...

  1. Your id should be unique. In your example you have inputs with the same ID.
  2. The name attribute is deprecated in HTML5, it should be the same as ID.

Here what I would do: Change to classes.

<?php for($i=0; $i<5; $i++){ ?>
    <input type="text" class="modify_album_title_input" value="" required=""/>
<?php } ?>

Then you'll be able to get your array like this:

var myArray = $('.modify_album_title_input');

Upvotes: 1

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35973

try this:

var arr = new Array();
$("input[name^='modify_album_title_input']").each(function(index){
    arr.push($(this).val());
});

Upvotes: 1

tymeJV
tymeJV

Reputation: 104795

Use .map()

var input_array= $("input[name='modify_album_title_input[]']").map(function() {
    return this.value;
}).get();

It only returns the first value in your code since that selector grabs a collection of elements, and simply trying .val() grabs the first one. map() will generate a nice array of values from the specified selector.

Also, you have repeating ID's, stop that! ID's must be unique.

Upvotes: 4

Related Questions