Reputation: 14270
I have an HTML template that contains a jQuery function that executes an Ajax request to my web server. The data in the response contains strings with car brand names and numbers which are used to set the value in an input checkbox for each particular car brand. Here's an example from the template:
<input type="checkbox" name="list" value="2">
<label for="brand">Mercedes</label>
I'm trying to use the following jQuery code to see if the input checkbox is checked for each car brand. index.name is a string and contains the car brand (e.g. "Mercedes") and index.id contains the value 2 which is a JavaScript number type (I confirmed this in the console):
$.each(data, function(key, index) {
if ( $('input[type=checkbox][value=index.id]').prop('checked', true) ) {
console.log("Checkbox is checked");
}
});
When I run the jQuery code, I'm getting this error:
Uncaught Error: Syntax error, unrecognized expression: input[type=checkbox][value=index.id]
Can anyone tell me what I'm doing wrong? I've read other Stackoverflow questions on how to do this and what I'm doing appears to be correct.
Upvotes: 1
Views: 392
Reputation: 780974
You need to quote the parameter to an attribute selector if it contains any special characters (in this case, the .
character):
$('input[type=checkbox][value="index.id"]')
However, this will looks for a checkbox whose value is the literal string index.id
. If you're actually trying to use the value of the expression index.id
, neither way will do it, since variables aren't expanded inside strings. You need to concatenate:
$('input[type=checkbox][value="' + index.id+ '"]')
or use an ES6 template literal:
$(`input[type=checkbox][value="${index.id}"]`)
Upvotes: 1