Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ampersand (&) symbol inside jQuery selectors

I have a <select> menu with a bunch of <option> tags, all populated from a database table.

I need to use a jquery selector such as $('option[value=d&c]') in order to find an option such as this one:

<option value="d&c">d&amp;c</option>

Note that the value attribute does not have an encoded ampersand (&amp;) in it, just a straight ampersand (&) because of how Zend Framework populates it.

Only problem is that jQuery chokes with the following error:

uncaught exception: Syntax error, unrecognized expression: [value=d&c]

It also won't accept $('option[value=d&amp;c]'). It's the ampersand messing it up, in either case. Does anyone know how to get around this limitation?

like image 382
fronzee Avatar asked Feb 15 '12 22:02

fronzee


3 Answers

You missed the quotes around the value

This works:

$('option[value="d&c"]')

jsFiddle

like image 134
Gabe Avatar answered Nov 15 '22 06:11

Gabe


Try escaping it...

$('option[value=d\\&c]')

jsFiddle.

...or use quotes, which is recommended in the documentation.

like image 29
alex Avatar answered Nov 15 '22 06:11

alex


It works when you set the option value in quotes:

$(function() {
    alert($("option[value='d&c']").text());       
});

http://jsfiddle.net/fGTRv/

like image 22
harpax Avatar answered Nov 15 '22 06:11

harpax