Hammad
Hammad

Reputation: 2137

How to get values of each input field using jquery having same name?

I am trying to get the values of each of the input field that are under same set. Below is my code:

Input field 1:

<input type="text" maxlength="255" name="amount[]" >

Input field 2:

<input type="text" maxlength="255" name="amount[]" >

and so on....the number of fields are variable.

Now I want to get the values the user typed in each of the field that is named . How to do that in jquery?

I have tried following code but it returns nothing:

$("input[name=amount[]]").val();

Upvotes: 2

Views: 10545

Answers (6)

Adil Shaikh
Adil Shaikh

Reputation: 44740

you can get all values in an array

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

console.log(values);

Demo ---> http://jsfiddle.net/BFjp5/

Upvotes: 8

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28548

Since there are multiple element with same name you need indexing:

$("input[name='amount[]']")[0].value;

Here is demo

and for getting all elements values:

$("input[name='amount[]']").each(function (i,v) {
    alert(this.value);
});

Here is demo

Upvotes: 2

arulmr
arulmr

Reputation: 8836

$("input[name='amount[]']")

This will get you a set of elements. You can get value of each of those elements by iterating over them.

$("input[name='amount[]']").each(function(){
    $(this).val();
});

Upvotes: 1

Thor
Thor

Reputation: 291

You don't!

The whole point of ID's in the DOM is that they are unique.

Upvotes: -4

Govind Singh
Govind Singh

Reputation: 15490

by javascript

function getValues(){
        var ids=document.getElementsByName('amount[]');
        var ary=new Array();

        for(var i=0;i<ids.length;i++){
            ary[i]=ids[i].value;
        }
        return ary;
    }

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try to pass the attribute value as a string since [ and ] are meta-characters,

var values = $("input[name='amount[]']")
                  .map(function(){ return $(this).val() })
                    .get().join('');

DEMO

Upvotes: 0

Related Questions