2

I have a select menu, it's options are ID'd like this:

<select>
<option id='order1|2'>1</option>
<option id='order2|2'>2</option>
<option id='order3|2'>3</option>
</select>

I want to select one dynamically with jQuery. In javascript, I can do

document.getElementById("order2|2").selected=true;

and that works fine. however, with jQuery

$("#order2|2").attr("selected","selected");

gives a bad expression error, so does any other command when I am working with it, such as

$("#order2|2").val();

I'm not sure what is happening. jQuery does not like the pipe symbol? Thanks.

3 Answers3

9

Use this selector:

$("#order2\\|2")

From jQuery selectors docs:

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\.

Reference:

Ian
  • 48,619
  • 13
  • 99
  • 109
2

You need to escape | with \\

$("#order2\\|2").prop("selected",true);

Demo --> http://jsfiddle.net/VzAQN/1/

Mohammad Adil
  • 44,013
  • 17
  • 87
  • 109
0

it is all in the documentation:

http://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/

akonsu
  • 27,402
  • 26
  • 115
  • 185
  • 2
    Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – bfavaretto May 20 '13 at 20:40