I have a problem with select option in html select element via JQuery. Next code demonstrate my problem:
$('select[name="location"] option[value=' + 'mercedes mercedes' + ']').attr('selected', true);
And i have simple html code for select with option value - "mercedes mercedes". When I run my script - i got exception:
"Error: Syntax error, unrecognized expression: [value=mercedes mercedes] throw new Error( "Syntax error, unrecognized expression: " + msg );"
When I delete whitespace - all is ok. Maybe anyone know - how to fix it?
I have a problem with select option in html select element via JQuery. Next code demonstrate my problem:
$('select[name="location"] option[value=' + 'mercedes mercedes' + ']').attr('selected', true);
And i have simple html code for select with option value - "mercedes mercedes". When I run my script - i got exception:
"Error: Syntax error, unrecognized expression: [value=mercedes mercedes] throw new Error( "Syntax error, unrecognized expression: " + msg );"
When I delete whitespace - all is ok. Maybe anyone know - how to fix it?
Share Improve this question edited Sep 27, 2012 at 17:41 VladislavLysov asked Sep 27, 2012 at 17:36 VladislavLysovVladislavLysov 6511 gold badge14 silver badges25 bronze badges 1- Don't mix double quotes and single quotes a lot. You will have to escape single quotes inside the outer single quotes. – Sully Commented Sep 27, 2012 at 17:39
3 Answers
Reset to default 13Put quotes around your option :
$('select[name="location"] option[value="' + 'mercedes mercedes' + '"]')
$('select[name="location"] option[value=' + 'mercedes mercedes' + ']')
results in
$('select[name="location"] option[value=mercedes mercedes]')
which is not a valid selector. Since the value has a space, you have to enclose it in quotes (like the other answers show).
From the docs:
value
: An attribute value. Can be either an unquoted single word or a quoted string.
If this is not a multiple select field, just call .val
:
$('select[name="location"]').val('mercedes mercedes');
The value with paces should be quoted in the selector:
$('select[name="location"] option[value="mercedes mercedes"]');
If you get that from a variable (most likely), you should do this:
$('select[name="location"] option[value="'+yourvariable+'"]');