Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery attribute selector variable that contains a quote?

I want to select an input box which has the following ID:

id="Peoples' Choice"

If I manually type in the selector with escape characters, it works:

$("[id='Peoples\\' Choice']")

But if I use a variable, it doesn't seem to work:

var theID = "Peoples' Choice";
var sel = "[id='" + theID + "']"
chk = $(sel);

This spews out a syntax error saying unrecognized expression. I even tried replacing the quote in theID with double-backslash+quote.

Help?

like image 409
ForeverLearnNeverMaster Avatar asked Sep 12 '25 05:09

ForeverLearnNeverMaster


2 Answers

You can escape the special characters in your variable prior to using it in your attribute selector.

You can use the following regex:

var sel = "[id='" + theID.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g,'\\$1') + "']"

DEMO

like image 80
Didier Ghys Avatar answered Sep 14 '25 21:09

Didier Ghys


ids can't have spaces in it. Just use peoples-choice.
From w3, http://www.w3.org/TR/html4/types.html

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

like image 45
elclanrs Avatar answered Sep 14 '25 21:09

elclanrs