Sam
Sam

Reputation: 27

how to store textbox values in array using jquery?

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.

Upvotes: 0

Views: 9039

Answers (2)

user3792555
user3792555

Reputation: 125

var newArray = [];
$( "input[name='control_text']" ).each(function() {
    newArray.push($( this ).val());
});
console.log(newArray);

you can also achieve it using .each function.

Upvotes: 2

VisioN
VisioN

Reputation: 145378

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.

Upvotes: 12

Related Questions