[jQuery] Creating array from selectors

So, i have this section of html:


<input type="text" id="inputA_1" value="ValueA" />
<input type="text" id="inputB_1" value="ValueB" />
<input type="text" id="inputC_1" value="ValueC" />
<input type="text" id="inputD_1" value="ValueD" />

And i want to build this basic java script variable


var postdata = {inputA: 'ValueA',
    inputB: 'ValueB',
    inputC: 'ValueC',
    inputD: 'ValueD'}

In reality there are approximately 100 variables. (Its a template builder).

Currently im doing it like this


function buildPostData(id){
    var postdata = {inputA: $("#inputA_"+id).val(), inputB: $("#inputB_"+id).val(), inputC: $("#inputC_"+id).val(), inputD: $("#inputD_"+id).val()};
}

Now, i KNOW there is a better way to do this. Im just not 100% sure on how to use the array.push function properly.

Here is what i have so far:


function buildPostData(id){
    var postdata = [];
    $("input[id$='_"+id+"']").each(function(){
        var id = $(this).attr("id");
        var value = $(this).val();
        
        //Now how to i push it into the array properly?
        postdata.push(id: value);
    });
}

Thanks alot
~Cody Woolaver

Your best bet would to be wrap the input in a named element (div, ul) and then check from there.

The following scrip gets all the inputs and makes an key => value array (what does JavaScript call it? Object notation or something. Two many names for the same thing! I call em associative arrays or dictionaries).


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
	var postData = {};
	$("#inputs input").each(function() {
		postData[this.id] = $(this).val();
	});
});
</script>
<div id="inputs">
	<input type="text" id="inputA_1" value="ValueA" />
	<input type="text" id="inputB_1" value="ValueB" />
	<input type="text" id="inputC_1" value="ValueC" />
	<input type="text" id="inputD_1" value="ValueD" />
</div>

You would need to push an array, onto that outer array.


postdata.push([id, value)];

But, you could also


// use object as assoc array/hash map
var postdata = {};
$("input[id$='_"+id+"']").each(function(){
    postData[this.id] = this.value;
});

Thankyou both :slight_smile: I got it