最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery exception when select option with whitespaces - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 13

Put 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+'"]');
发布评论

评论列表(0)

  1. 暂无评论