Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate attribute selector with variable does a syntax error

This code works, the class is added, but I am receiving an error.

console.log(key);    //first_date
$('*[name='+key+']').addClass('error');

ERROR:

Uncaught Error: Syntax error, unrecognized expression: `*[name=]`

What is wrong here?

<input id="date-picker-1" type="text" class="date-picker form-control hasDatepicker" name="first_date">
like image 445
user2990084 Avatar asked Dec 28 '25 10:12

user2990084


1 Answers

The error is happening because your key variable is empty. '*[name='+key+']' is evaluating to '*[name=]'. To avoid the error, you can wrap your key variable in quotes:

$('*[name="'+key+'"]').addClass('error');

This way you will not get the error as instead of trying to evaluate *[name=] it will try to evaluate *[name=""]. However as your key variable appears to be empty, this will probably not produce the result you're looking for.

Double check your code to ensure key is set prior to addClass being called.


In fact, if what you say is true that the "error" class is added, I imagine your code here is being executed twice - once when key is empty, and again when key is in fact equal to "first_date".

like image 190
James Donnelly Avatar answered Dec 30 '25 22:12

James Donnelly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!