1

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?

5
  • 1
    can you please put your html code or create a fiddle? Commented Aug 24, 2013 at 7:06
  • Where do you need to see retval? Is it in scope there? Commented Aug 24, 2013 at 7:09
  • 3
    Probably in one iteration its making retval=1 and in the next resetting it back to 0, put an alert in else block and then debug. Commented Aug 24, 2013 at 7:09
  • use console.log instead of alerts. It's much easier to see what's happening than getting stupid boxes popping up everywhere. Commented Aug 24, 2013 at 7:17
  • What are you using retval for? I think there's probably a better solution to whatever problem you're facing than the one you're trying to use. Commented Aug 24, 2013 at 7:24

4 Answers 4

1

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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;
    }
});

Comments

0

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');
    }
});

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.