Varun Varun - 6 months ago 46
jQuery Question

jquery :contains giving error: jquery-1.12.3.js:1502 Uncaught Error: Syntax error, unrecognized expression: contains("sys")

I am trying to implement a filter which will filter "pre" html element when text matches with what user is entering in an input html element.

But it doesn't seems to work when i try to check it with what user is entering, but works if i hardcode the text to be searched.

Here's my js script:

$(document).ready(function(){
$("#input")
.change( function () {
var filter = $(this).val();
if(filter) {
$("#list").find("pre:contains(\""+filter+"\")").show()
$("#list").find("pre:not(contains(\""+filter+"\"))").hide()

} else {

}
return false;
})
.keyup( function () {

$(this).change();
}); });


If i hardcode the "filter" to some string in "pre" elements it works.
for eg: one of the string has "sys" in it, so if i hardcode like:
$("#list").find("pre:contains("sys")").hide()
: it hides the element.

Answer

The second line for hiding,

$("#list").find("pre:not(contains("+filter+"))").hide()

is converted to

$("#list").find("pre:not(contains(sys)").hide()

which throws unrecognized expr for (contains(..))


It should be with : for contains() - final evaluation to :not(:contains(...))

$("#list").find("pre:not(:contains("+filter+"))").hide()
//                       ^

Fiddle Demo

Comments