Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
218 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...