1

I have an issue related to converting html inputs names to a javascript object. For example I have an input:

<input type="checkbox" name="product[1]">
<input type="checkbox" name="product[2]">

and I have javascript code:

var data = {};
$('input').each(function(){
    // need to do something like 
    data[$(this).attr('name')] = $(this).attr('checked');
})

I expect to get data object like this;

data = {
    product: {
        1: 'checked',
        2: 'checked'
    }
}

Is this possible without using regular expressions?

5
  • tough to tell what you want from the example. what is the name of the input in that example? Commented Mar 1, 2013 at 16:49
  • He wants a result that is two levels deep, as the value of name implies. Commented Mar 1, 2013 at 16:49
  • Frits van Campen is right. I need two levels deep array/object Commented Mar 1, 2013 at 16:51
  • @FritsvanCampen the question was edited after that comment :) Commented Mar 1, 2013 at 16:54
  • can you use different input names? Commented Mar 1, 2013 at 16:55

3 Answers 3

0

Replacing your variables with literal values, you get this:

data["product[1]"] = true;

The square brackets have no meaning as they are inside a string, so you won't get any result.

There are ways around this. You could use eval: eval("data."+this.name+" = "+(this.checked?"true":"false"));

However since eval is best avoided, try this:

var m = this.name.match(/(.*)\[(\d+)\]/);
data[m[0]][m[1]] = this.checked;
Sign up to request clarification or add additional context in comments.

1 Comment

eval("data."+this.name+" = "+(this.checked?"true":"false")); - GREAT!!! Thanks! I have tried eval(this.name) but got "undefined variable product...". Thank you too much!
0

Yes in general it is possible. You can do the following:

var noregexp = $(this).attr('name').split("[");
if (noregexp.length==2) {
    //should be
    var the_name = noregexp[0];
    var the_index = noregexp[1].substr(0,noregexp[1].length-1); //this will get the index with removed ]
}

I made this up from my mind. It's not a beautiful solution but one without regexp as you wished.

Comments

0

You can get a data structure the way you need using:

var data = {product: []};
$('input').each(function(){
    data.product[$(this).attr('name').match(/product\[([\d]*)\]/)[1]] = $(this).prop('checked');
})
console.log(data);

Check thid demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.