jqueryjsonjquery-selectors

Error when using jQuery selectors pulled from a JSON configuration


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


Solution

  • 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>