最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to parse input[] values and put them into a Javascript Array - Stack Overflow

programmeradmin3浏览0评论

Let's say i have this:

<form id='foo'>
 <input name='bar[name]' />
 <input name='bar[age]' />
</form>

How can i get the values of array inputs within the form foo and put them into an associative array/object like this:

var result = {bar:{name:'blah',age:21}};

P.S. I don't want to use any frameworks for this.

Let's say i have this:

<form id='foo'>
 <input name='bar[name]' />
 <input name='bar[age]' />
</form>

How can i get the values of array inputs within the form foo and put them into an associative array/object like this:

var result = {bar:{name:'blah',age:21}};

P.S. I don't want to use any frameworks for this.

Share Improve this question edited Aug 26, 2011 at 21:33 CodeOverload asked Aug 26, 2011 at 21:26 CodeOverloadCodeOverload 48.5k56 gold badges133 silver badges223 bronze badges 4
  • 4 By "Pure JavaScript" I take it you mean "Without using JavaScript written by other people, such as the jQuery or YUI teams"? (As opposed to "Without Flash" or "Without DOM"?) – Quentin Commented Aug 26, 2011 at 21:29
  • 2 Technically, jQuery is "pure JavaScript." Do you want to understand how read form elements with plain-old DOM or do you want to be more productive and Get Stuff Done? – Matt Ball Commented Aug 26, 2011 at 21:30
  • is querySelectorAll also pure? – pimvdb Commented Aug 26, 2011 at 21:32
  • querySelectorAll is as impure as DOM, it is an API that browsers expose to JS, not part of JS itself. – Quentin Commented Aug 26, 2011 at 21:32
Add a comment  | 

5 Answers 5

Reset to default 5

I needed to do this myself and after finding this question I didn't like any of the answers: I don't like regex and the others are limited.

You can get the data variable many ways. I'll be using jQuery's serializeArray method when I implement this.

function parseInputs(data) {
    var ret = {};
retloop:
    for (var input in data) {
        var val = data[input];

        var parts = input.split('[');       
        var last = ret;

        for (var i in parts) {
            var part = parts[i];
            if (part.substr(-1) == ']') {
                part = part.substr(0, part.length - 1);
            }

            if (i == parts.length - 1) {
                last[part] = val;
                continue retloop;
            } else if (!last.hasOwnProperty(part)) {
                last[part] = {};
            }
            last = last[part];
        }
    }
    return ret;
}
var data = {
    "nom": "123",
    "items[install][item_id_4]": "4",
    "items[install][item_id_5]": "16",
    "items[options][takeover]": "yes"
};
var out = parseInputs(data);
console.log('\n***Moment of truth:\n');
console.log(out);

You can map the elements to an object like this.

function putIntoAssociativeArray() {

    var 
        form = document.getElementById("foo"),
        inputs = form.getElementsByTagName("input"),
        input,
        result = {};

    for (var idx = 0; idx < inputs.length; ++idx) {
        input = inputs[idx];
        if (input.type == "text") {
            result[input.name] = input.value;
        }
    }

    return result;
}
var form = document.getElementById( 'foo' );
var inputs = form.getElementsByTagName( "input" );
var regex = /(.+?)\[(.+?)\]/;
var result = {};
for( var i = 0; i < inputs.length; ++i ) {
    var res = regex.exec( inputs[i].name );
    if( res !== null ) {
        if( typeof result[ res[1] ] == 'undefined' ) result[ res[1] ] = {};
        result[ res[1] ][ res[2] ] = inputs[i].value;
    }
}
var inputs = document.getElementsByTagName('input');
var field_name, value, matches, result = {};
for (var i = 0; i < inputs.length; i++) {
   field_name = inputs[i].name;
   value = inputs[i].value;

   matches = field_name.match(/(.*?)\[(.*)\]/);

   if (!results[matches[0]]) {
       results[matches[0]] = {};
   }
   results[matches[0]][matches[1]] = value;
}

This will get you the elements:

 var result = {};
    var elements = document.forms.foo.getElementsByTagName("input");
    for(var i = 0; i < elements.length; i++)
    {
       /* do whatever you need to do with each input */
    }
发布评论

评论列表(0)

  1. 暂无评论