Let say I have JSON like this:
{
"foobar": "data foobar",
"foo": "data foo",
"bar": "data bar",
"baz": "data baz",
"qux": "data qux",
"quux": "data quux",
"corge": "data corge",
"grault": "data grault",
"garply": "data garply",
"waldo": "data waldo",
"fred": "data fred",
"plugh": "data plugh",
"xyzzy": "data xyzzy",
"thud": "data thud"
}
How can I fill the input box with the data using the key
let data = {
"foobar": "data foobar",
"foo": "data foo",
"bar": "data bar",
"baz": "data baz",
"qux": "data qux",
"quux": "data quux",
"corge": "data corge",
"grault": "data grault",
"garply": "data garply",
"waldo": "data waldo",
"fred": "data fred",
"plugh": "data plugh",
"xyzzy": "data xyzzy",
"thud": "data thud"
}
$('input[name=foobar]').val(data['foobar']);
$('input[name=foo]').val(data['foo']);
$('input[name=bar]').val(data['bar']);
...
As you can see, the above code gives manual filling. I don’t want to use looping, but I want to get value of the related jquery selector string like this:
$('input[name=foobar]').val(data[/=(w+)]/.exec(this.selectorstring)[1]]);
I expect this.selectorstring
returns 'input[name=foobar]'
. Is it possible to do this in Javascript / jQuery?
2
Answers
Since you do not want to use loops and prefer manual copy-pasting, you can do this:
Or, as @freedomn-m suggested, use a variable instead:
You cannot directly put the selector into
this.selectorstring
without function context.Here is another option which like the others is also quick and easy to copy and paste for a lot of lines. It is a simple function where you reference it just like $(selector).val but instead reference the function name and pass the data object (or not but I prefer to pass it).