Concatenate Attribute Selector with Variable Performs Syntax Error

This code works, the class has been added, but I am getting an error.

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

      

ERROR:

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

      

What's wrong here?

<input id="date-picker-1" type="text" class="date-picker form-control hasDatepicker" name="first_date">

      

+3


source to share


1 answer


The error is happening because your variable is key

empty. '*[name='+key+']'

evaluated before '*[name=]'

. To avoid the error, you can wrap the variable key

in quotes:

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

      

This way you won't get the error, instead of trying to evaluate *[name=]

, it will try to evaluate *[name=""]

. However, since your variable key

appears to be empty, this probably won't lead to the result you're looking for.



Double check your code to make sure it is key

set before calling addClass

.


In fact, if you are telling the truth that the class "error" was added, I think your code here is executed twice - once when it is key

empty, and again when key

it is actually equal to "first_date".

+4


source







All Articles