Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery escape apostrophe in option value

Tags:

jquery

I want to select the option with a particular value. And the value of the element contains apostrophe in it. In this case it does not select the element properly.

var selectedValue= "Test'1";
jQuery("option[value='" + selectedValue + "']"); // does not find option with value as "Test'1"

Sample Fiddle: http://jsfiddle.net/JSWorld/26JTy/4/

Here it does not alert, when I select an option that has an apostrophe in it.

like image 850
Chubby Boy Avatar asked Sep 15 '25 14:09

Chubby Boy


2 Answers

Escape using double back-slashes:

var selectedValue = jQuery(this).val().replace("'", "\\'").replace('"', '\\"');

Your updated fiddle: http://jsfiddle.net/abhitalks/26JTy/6/

like image 152
Abhitalks Avatar answered Sep 18 '25 08:09

Abhitalks


This would give you the same problem if you have any values with double quotes ("), but you could flip the single and double quotes in your code:

var selectedValue= "Test'1";
jQuery('option[value="' + selectedValue + '"]'); 

http://jsfiddle.net/26JTy/5/

like image 44
Zeth Avatar answered Sep 18 '25 09:09

Zeth