I want to allow the user to enter in a search string and I want to return the count of how many times that search item is found. I can get this to work if I hard code the search value into the ‘contains’ method, but as soon as I store the search value into a variable it no longer works.
HTML:
<div class="myTest">this</div>
<div class="myTest">this</div>
<div class="myTest">that</div>
<div class="myTest">that</div>
<div class="myTest">this</div>
<div id="howMany"></div>
JAVASCRIPT:
$(function() {
var myVal= "that";
var existingList = $("div:contains(myVal) + .myTest").length;
$("div[id*='howMany']").html(existingList);
})
A few errors in your code :
+in jQuery selectors doesn’t do what you think it doesmyValand not the value ofmyValin the selector#to look for an element with a given idYou could search using
But this wouldn’t work with strings containing double quotes. For any kind of string, I would rather suggest
To issue the number of found results, use