How To Convert Input Name To JavaScript Array
I have an issue related to converting html inputs names to a javascript object. For example I have an input: Copy
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;
Solution 2:
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.
Solution 3:
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
Post a Comment for "How To Convert Input Name To JavaScript Array"