How to get all the values of input array element jquery

JavascriptHtmlJquery

Javascript Problem Overview


Here is my html input elements

<input type="text" name="pname[]" value="" />
<input type="text" name="pname[]" value="" />
<input type="text" name="pname[]" value="" />
<input type="text" name="pname[]" value="" />
<input type="text" name="pname[]" value="" />
<input type="text" name="pname[]" value="" />

How can I get all the values of pname array using Jquery

Javascript Solutions


Solution 1 - Javascript

By Using map

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

Solution 2 - Javascript

You can use .map().

> Pass each element in the current matched set through a function, producing a new jQuery object containing the return value.

As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.

Use

var arr = $('input[name="pname[]"]').map(function () {
	return this.value; // $(this).val()
}).get();

Solution 3 - Javascript

Use:

function getvalues(){
var inps = document.getElementsByName('pname[]');
for (var i = 0; i <inps.length; i++) {
var inp=inps[i];
    alert("pname["+i+"].value="+inp.value);
}
}

Here is Demo.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3707303View Question on Stackoverflow
Solution 1 - JavascriptMahendra JellaView Answer on Stackoverflow
Solution 2 - JavascriptSatpalView Answer on Stackoverflow
Solution 3 - JavascriptVedant TerkarView Answer on Stackoverflow