views:

996

answers:

4

Hi! I have a jquery selector that looks like:

var val = "John's cars";
$('#subject input[value="'+val+'"]')

This works just fine in Firefox, Chrome, Internet Explorer 8, but not in IE 6 or IE7. The problem is the ' in the text search for. Someone has any idea how to work around this problem except to loop through all inputs in question and do a string compare?

+3  A: 

Try this:

var val = "John's cars";
$('#subject input').filter(function() {
    return this.value == val;
});
Gumbo
Works like a charm, thanks
Ulf Lindback
+2  A: 

Try escaping the ' with a backslash

var val = "John\'s cars";
$('#subject input[value="'+val+'"]')

from jQuery

Special characters in selectors

If you wish to use any of the meta-characters described above as a literal part of a name, you must escape the character with a backslash (). Since Javascript uses the backslash for escape sequences in string literals, you must use two backslashes (\) in string literals so that a single backslash will be put into the string.

Example:

"#foo\\:bar"
"#foo\\[bar\\]"
"#foo\\.bar"

The full list of characters that need to be escaped: #;&,.+*~':"!^$[]()=>|/

EDIT:

since the value is in a string literal, it needs to be double-escaped. So this works

var val = "John\\'s cars";
$('#subject input[value="'+val+'"]')

Thanks to bobince for pointing it out.

Russ Cam
This does actually not work (at least not in IE6)
Ulf Lindback
@Ulf - which version of jQuery are you using?
Russ Cam
I'm using jQuery 1.3.2
Ulf Lindback
Hmmm... strange. It doesn't seem to work in Firefox 3.5 either. Looks like using `filter` is the best way
Russ Cam
Your `\'` is in a JavaScript string literal, where it means `'`. You need another level of escaping: `"John\\'s cars"` to get the real backslash character into the selector string. [dear lord, StackOverflow's own handling of backslashes is broken...]
bobince
@bobince - thanks! I thought it may be something small that I was missing :)
Russ Cam
A: 

I bet it's the apostrophe in the search value - try escaping it using

"John\'s cars"
James Kolpack
A: 

And performance ??? What about it ?? Using filter() would loop from the loop that jQuery already creates ...

1ukaz
In my case, performance doesn't really matter. Do you have another solution that would perform better?
Ulf Lindback