26

I have many inputs on a page. I want to create an associative array with each input's name and value using jQuery. I've tried:

<input class="activeInput" type="text" name="key1" value="red">
<input class="activeInput" type="text" name="key3" value="France">

inputValues = $('.activeInput').val();

EDIT - Thanks to the insightful comments, it seems maybe creating an object is a better way to go. Any suggestions on how to create an object instead?

4
  • 1
    .val() only gets the value of the first input. Have you tried anything else? Commented Oct 23, 2012 at 18:17
  • in first view(reading ) title i thought you want to get the keyboard key value Commented Oct 23, 2012 at 18:23
  • 1
    @DonnyP half of the answers below create an object. Commented Oct 24, 2012 at 3:12
  • Possible yo want like there stackoverflow.com/questions/5550220/… Commented Oct 8, 2015 at 8:10

6 Answers 6

55

You can use .each() to iterate over the elements and add the names and values to a map (a plain object) like this:

var map = {};
$(".activeInput").each(function() {
    map[$(this).attr("name")] = $(this).val();
});

alert(map.key1); // "red"

See it in action.

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

2 Comments

Hey Jon, if I had for instance 10 inputs with the same class name, how can I capture those using the code above in a comma separated field. I just need a long string of their values, separated by a comma.
@user1011713: Use .map to get $(this).val() from each element, then Array.join to concatenate the values.
23

To create an array of values you can do this:

var $inputValues = $('.activeInput')
  .map((i, el) => el.val())
  .toArray();

To create an object with keys and values you can do this:

var data = $('.activeInput')
  .toArray()
  .reduce((accumulator, element) => {
    accumulator[element.name] = element.value;
    return accumulator;
  }, {});

4 Comments

@AdamFriedman I would like to point out that this is not a syntactic error, and it was actually removed in an earlier edit. I do however prefer this style for readability.
Sorry, not syntax error per se, but your browser will throw an error if in your map() function you use "this" instead of "$(this)".
@AdamFriedman Oh that's funny, you're actually right. I was told last year that I should remove it because this would already be a jQuery object in this context... You did miss a spot though.
For clarity el.val() should be $(el).val()
6

By running them through a loop you can create an object with string accessible values. Javascript doesn't have the concept of an associative array, but using bracket syntax you can access properties on an object in much the same way an associative array works in PHP.

var values = {};
$('.activeInput').each(function() {
    values[this.name] = this.value;
});

console.log(values['key1'], values['key3']);
// Note, this is the same as above.
console.log(values.key1, values.key3);

In your console you should see: red France

Here is a JsFiddle http://jsfiddle.net/rEtVt/ for it.

This is also referred to as a hashmap (concept) used for quick lookups.

6 Comments

This creates an array with properties. Not an associative array.
@KevinB is correct. I updated to reflect that. Also not sure why the other answers use JQuery in the loop to get the name and value when you can directly access them as this.name, this.value.
@earl3s: this.name is fine, but .val() works on <select> elements while this.value does not.
@Jon yes, but these are <input> elements!
@KevinB: Sure, but since jQuery is in the picture anyway why not write more generic code?
|
2
var inputValues = new Array();
$('input').each(function(){
    inputValues[$(this).attr('name')] = $(this).val();
});

That is assuming, of course, that you want the value of all inputs.


That being said, many reasons not to use and Array have been brought to my attention.

9 Comments

... Why is inputValues an array if you are treating it like an object? After your each the array still has a length of 0.
because this ... "I want to create an associative array"
Javascript doesn't have associative arrays, it has objects. var inputValues = {}
i suppose then ... habit. the advantage to using on obj being?
I would compare using an array in this way to using this: var inputValues = new String();. Here's an example: jsfiddle.net/5BkbQ Notice how you get the exact same results using new String, new RegExp, and new Array. This because they are all objects. Why store object-like values in an array? It makes no sense in this case. Just because it works doesn't mean you should do it.
|
1

If you need to serialize form for ajax submission then you should have a look at serialize and serializeArray jQuery methods. Special cases may occur when you have many inputs with the same name attribute that have to make array on the server.

Otherwise, I would call jquery serializeArray on the form element and iterate over its results to convert it into object.

UPD: added example http://jsfiddle.net/zQNUW/

Comments

-1

Try this:

var values = new Object() // creates a new instance of an object
$('.activeInput').each(function() {
    values[$(this).attr('name')] = $(this).val()
})

To check the object properties:

output = ""
for (property in values) {
  output += property + ': ' + values[property]+'; ';
}
alert(output)

2 Comments

.val() only gets the value of the first input. (and this answer just so happens to have the exact same code as in the question which isn't working. )
Close, but values.$(this).attr('name') won't work. values[$(this).attr('name')]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.