Search code examples
javascriptjquerycss-selectors

How to get selector string with jQuery?


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?


Solution

  • Since you do not want to use loops and prefer manual copy-pasting, you can do this:

    (s => s.val(data[/=(\w+)\]/.exec(s.selector)[1]]))($('input[name=foobar]'));
    

    Or, as @freedomn-m suggested, use a variable instead:

    var s = "input[name=foobar]"; $(s).val(data[/=(\w+)]/.exec(s)[1]]);
    

    You cannot directly put the selector into this.selectorstring without function context.

    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"
      };
      
      (s => s.val(data[/=(\w+)\]/.exec(s.selector)[1]]))($('input[name=foobar]'));
      (s => s.val(data[/=(\w+)\]/.exec(s.selector)[1]]))($('input[name=foo]'));
      (s => s.val(data[/=(\w+)\]/.exec(s.selector)[1]]))($('input[name=bar]'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <pre>
    <input name="foobar" />
    <input name="foo" />
    <input name="bar" />