0

I have two text boxes with the same name control_text but their values are different. I want to store all my text box values in an array using jQuery.

HTML

<input type="text" name="control_text" placeholder="Text Label Image" class="required" id="control_text" value="firstvalue" />
<input type="text" name="control_text" placeholder="Text Label Image" class="required" id="control_text" value="secondvalue" />

JavaScript

var test_arr = $("input[name='control_text']");
$.each(test_arr, function(i, item) {
    // i = index, item = element in array
    alert($(item).val());
});

The above code is displaying the values of text boxes individually. I don't want to alert these values individually, I want to alert both at once with comma separator similar to (firstvalue, secondvalue). Any help is appreciated.

1
  • Its also possible on submit, to get the results in an array format via the serialize Array function - api.jquery.com/serializeArray $('form').submit(function() { console.log($(this).serializeArray()); return false; }); Commented Nov 3, 2012 at 0:06

2 Answers 2

12

Use map() method:

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

A side note: elements in a single page should have unique IDs, so check your markup for validity.

Sign up to request clarification or add additional context in comments.

2 Comments

It's worth mentioning you'll need to apply .get() additionally, to get real js array.
@zerkms Yeah, I always forget about it :) Thanks!
2
var newArray = [];
$( "input[name='control_text']" ).each(function() {
    newArray.push($( this ).val());
});
console.log(newArray);

you can also achieve it using .each function.

1 Comment

I've tried a dozen answers and this is the only one that worked for some reason... Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.