0

I have a JSON object with jQuery selectors and values inside it. Special characters inside the selectors have (I think) been properly escaped. Here is what the JSON looks like:

var config = [{
    "fieldname": "First name",
    "selector":"\"[id$='txtFirstName']\"",
    "value": "Bob"
  },
  {
    "fieldname": "Last name",
    "selector": "\"[id$='txtLastName']\"",
    "value": "Smith"
  }
];

I have code that attempts to walk through this data, and apply the relevant value to the control indicated by the selector. That code looks like this:

$(config).each(
  function() {
    console.log('selector:')
    console.log(this.selector);
    var element = $(this.selector);
    element.val(this.value);
  }
)

When that code runs, I get this output:

"selector:"
"\"[id$='txtFirstName']\""

Followed by this error:

Error: Syntax error, unrecognized expression:
\&quot;[id$='txtFirstName'</a>\&quot;"

It looks like the double-quotes are being encoded (again) as the selector is pulled out. Why would that be? And how can I prevent it?

JSFiddle

5
  • 1
    you shouldn't put explicit quotes in the selector property.
    – Barmar
    Commented Apr 15 at 16:43
  • Just use "selector":"[id$='txtFirstName']",
    – Barmar
    Commented Apr 15 at 16:43
  • 1
    Please don't try to link to a JSFiddle. Use a Stack Snippet instead (or in addition) Commented Apr 15 at 16:52
  • If you expand your code by hand, you would get $(""[id$='txtLastName']""); which is clearly rubbish. Your selector should not be surrounded with " - fix the selector: "selector": "[id$='txtFirstName']",
    – fdomn-m
    Commented Apr 15 at 17:47
  • The selector itself does include the double-quotes, but the code that uses it does not. So the final result is simply $("[id$='txtLastName']"). The answer from @Hardik Uchdadiya resolved the issue. Commented Apr 16 at 19:47

1 Answer 1

1

Here you go, it resolves your issue, you are missing the word eval.

$(document).ready(function(){

var config = [{
    "fieldname": "First name",
    "selector":"\"[id$='txtFirstName']\"",
    "value": "Bob"
  },
  {
    "fieldname": "Last name",
    "selector": "\"[id$='txtLastName']\"",
    "value": "Smith"
  }
];

$(config).each(
  function() {
    console.log('selector:')
    console.log(this.selector);
    var element = $(eval(this.selector));
    element.val(this.value);
  }
)

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<html>

<body>
First name: &nbsp;
<input type="text" id="txtFirstName" name="txtFirstName" value=""/>

Last name: &nbsp;
<input type="text" id="txtLastName" name="txtLastName" value=""/>
</body>
</html>

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.