tmnd91
tmnd91

Reputation: 449

from html "array" to javascript array

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

Answers (3)

Paul S.
Paul S.

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

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382132

var obj = {};
$('#all [id^=search]').each(function() {
   obj[this.id.match(/\[(.*)\]/)[1]] = this.value;
});

DEMONSTRATION

Upvotes: 1

Barney
Barney

Reputation: 16456

jQuery provides $(form).serializeArray() as documented on their API site (always worth a quick look, that one).

Upvotes: 1

Related Questions