Ulf Lindback
Ulf Lindback

Reputation: 14170

JQuery selector problem in Internet Explorer

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?

Upvotes: 2

Views: 3924

Answers (3)

Russ Cam
Russ Cam

Reputation: 125488

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.

Upvotes: 3

James Kolpack
James Kolpack

Reputation: 9382

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

"John\'s cars"

Upvotes: 0

Gumbo
Gumbo

Reputation: 655239

Try this:

var val = "John's cars";
$('#subject input').filter(function() {
    return this.value == val;
});

Upvotes: 4

Related Questions