Chubby Boy
Chubby Boy

Reputation: 31072

jQuery escape apostrophe in option value

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.

Upvotes: 4

Views: 5485

Answers (3)

Sagar Thatte
Sagar Thatte

Reputation: 75

The following worked for me in my case:

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

Upvotes: 1

Zeth
Zeth

Reputation: 875

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/

Upvotes: 1

Abhitalks
Abhitalks

Reputation: 28437

Escape using double back-slashes:

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

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

Upvotes: 7

Related Questions