Reputation: 449
i've a html page that is made quite like this:
<table id="all">
<tr><td><input type="text" name="search[id]" id="search[id]"></input></td></tr>
<tr><td><input type="text" name="search[name]" id="search[name]"></input></td></tr>
..........ecc ecc..........
</table>
i want with javascript or jquery achieve an array made like this:
{
id:"<value in search[id]>",
name:"<value in search[name]>",
....ecc ecc...
}
the keys of the array aren't static so i can't name them statically in the code. i tried with $("#search") but i haven't been lucky :( Thank you very much for the help! and sorry for the noob question!
Upvotes: 0
Views: 101
Reputation: 66324
This is do-able in native JavaScript; assuming your HTML
function nameToObj(queryName, nodes, context) { // `nodes`, `context` optional
var o = {}, i, j = queryName.length; // var what we'll need
context || (context = document);
// if `context` falsy, use `document`
nodes || (nodes = context.getElementsByTagName('input'));
// if `nodes` falsy, get all <input>s from `context`
i = nodes.length; // initial `i`
while (i--) { // loop over each node
if (nodes[i].name.slice(0,j) === queryName) { // test
o[nodes[i].name.slice(j+1,-1)] = nodes[i].value;
// match, append to object
}
}
return o; // return object
}
nameToObj('search'); // Object {name: "", id: ""}
Upvotes: 0
Reputation: 382132
var obj = {};
$('#all [id^=search]').each(function() {
obj[this.id.match(/\[(.*)\]/)[1]] = this.value;
});
Upvotes: 1
Reputation: 16456
jQuery provides $(form).serializeArray()
as documented on their API site (always worth a quick look, that one).
Upvotes: 1