Reputation: 291
I have a table which has id 'myTable'. Now there is a textbox in which I write down the item name to find whether it exists in the myTable cell or not. To do this I have written the following code -
var retval=0;
var search = $("#searchitem").val().trim();
$("table#myTable tr td").filter(function() {
if($(this).text() == search){retval=1;alert('Same item found');}
else{retval=0;}
});
The problem is that, when it finds the same item in the table cell it shows the alertbox. But the value of my variable retval
never changes. It always shows 0
. How can I solve it?
Upvotes: 1
Views: 2755
Reputation: 2988
Try this code
var search = $("#searchitem").val().trim();
var filteredData = $("table#myTable tr td").filter(function(element, index)
{
return $(element).text() == search;
});
now this code return array of TD elements which satisfy the condition.
Upvotes: 0
Reputation: 449
I think what you are trying to accomplish could be done by using :contains() selector, like this:
var search = $("#searchitem").val().trim();
var retval = $("table#myTable tr td:contains('"+search+"'") ? 1 : 0;
I haven't tested it but I'm almost sure it works. It's a much more cleaner approach and surely more readable.
jQuery :contains() docs: http://api.jquery.com/contains-selector/
Upvotes: 1
Reputation: 17576
change the variable value only if found , because you assign the variable to 0 at the beginning.
var retval=0;
var search = $("#searchitem").val().trim();
$("table#myTable tr td").filter(function() {
if($(this).text() == search){
retval=1;
alert('Same item found');
}
});
Upvotes: 0
Reputation: 15497
please try return false
like this
var retval=0;
var search = $("#searchitem").val().trim();
$("table#myTable tr td").filter(function() {
if($(this).text() == search){
retval=1;
alert('Same item found');
return false;
}else{
retval=0;
}
});
Upvotes: 0