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?
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
id
s 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 (".").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With