chrismanderson
chrismanderson

Reputation: 4813

Nested single/double quotes in Javascript/jQuery

I had thought that single/double quotes were interchangeable in Javascript. So in a jQuery function, could anyone explain why:

$('input:radio[name='+foo+'][value='+bar+']').attr('checked', true);

works, but

$('input:radio[name="+foo+"][value="+bar+"]').attr('checked', true);

doesn't? (If foo and bar are both strings.)

Does nesting double in single/single in double quotes not work?

Upvotes: 3

Views: 5171

Answers (6)

user1663548
user1663548

Reputation: 11

You don't need to put quotes around foo.

$('input:radio[name=food]') 

will work on it's own.

Upvotes: 1

Šime Vidas
Šime Vidas

Reputation: 186083

'input:radio[name="+foo+"][value="+bar+"]'

doesn't work because it's one (single) large string. You are not injecting the foo and bar variables.

You have to write it like so:

'input:radio[name="' + foo + '"][value="' + bar + '"]' 

A simplified example:

'Value: " + foo + "' (BAD)

'Value: "' + foo + '"' (GOOD)

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385385

"Interchangeable" does not mean "arbitrary".

It's your choice whether to delimit a string literal with a set of single or of double quotes, but the start and end delimiters for a single string literal must still, of course, be the same.

Upvotes: 2

cdeszaq
cdeszaq

Reputation: 31300

If you use one quote type inside another, in most modern JavaScript engines, it will treat the inner, alternate-type quotes as quote characters rather than string delimiters.

Upvotes: 2

Adam Terlson
Adam Terlson

Reputation: 12730

It works, but they need to match. Your opening quote is single, then you're attempting to close it with a double. This doesn't work.

//\/SINGLE          \/DOUBLE
$('input:radio[name="+foo+"][value="+bar+"]').attr('checked', true);

The effect of this is that javascript doesn't know that you're trying to terminate the string literal and append the variable value. It assumes that you are still in the string literal and want the " character as part of it. As long as the quotes match there's no difference between this:

var foo = "hello " + world;

and

var foo = 'hello ' + world;

Upvotes: 2

Naftali
Naftali

Reputation: 146350

you cannot nest variable in jQuery, i know you can do that in php but not jQuery, just use your 1st option of:

$('input:radio[name='+foo+'][value='+bar+']').attr('checked', true);

or do this (i changed your second option a bit):

$('input:radio[name="'+foo+'"][value="'+bar+'"]').attr('checked', true);

Upvotes: 2

Related Questions