user1450749
user1450749

Reputation: 183

JQuery filter using :contains

I am new to all this and struggling with identifying a parent element when using :contains to filter a bunch of divs? My end result is to have 3 buttons that when clicked check if a div contains a specific word and if so apply a class to the containing div, and another class to all other divs.. essentially hiding and showing them.

I have a fiddle which doesn't work but show the idea I am trying to create.

The code that I know doesn't work but gives the process is;

$(".manchester").click(function (e) {
    if ($('.address:contains("Manchester")').length) {
        $('holder').addClass('visible');
    }
    if ($('.address:contains("London")').length) {
        $('.holder').addClass('invisible');
    }
    if ($('.address:contains("Paris")').length) {
        $('.holder').addClass('invisible');
    }
    e.preventDefault();
});

and the fiddle lives at http://jsfiddle.net/2fEzS/

Upvotes: 4

Views: 11049

Answers (2)

Ram
Ram

Reputation: 144689

The logic is wrong, you don't actually filter the elements, instead of defining several handlers, you can minify the code by using textContent of the clicked element. I'd suggest:

$(".filter div").click(function(e) {
    $('.holder').hide() // hide all the selected elements
                .filter(':contains(' + $(this).text()  + ')')
                .show(); // show the filtered elements
});

Or:

$(".filter div").click(function (e) {
    $('.holder').addClass('invisible')
                .removeClass('visible')
                .filter(':contains(' + $(this).text()  + ')')
                .removeClass('invisible')
                .addClass('visible');
});

http://jsfiddle.net/kdRzQ/

Note that div element shouldn't be used as a button and it doesn't have a default action to be prevented, so preventDefault doesn't do anything in your code. Also if there are many elements in the document, it would be better to cache the elements outside the context of the click handler:

var $holders = $('.holder');   
$(".filter div").click(function (e) {
    $holders.addClass('invisible') // ...
});

Upvotes: 7

putvande
putvande

Reputation: 15213

You are hiding all the divs with the class .holder instead of just the one that affect the contains bit.

Change your code to:

$(".manchester").click(function (e) {
    $('.address:contains("Manchester")').closest('.holder').addClass('visible');
    $('.address:contains("London")').closest('.holder').addClass('invisible');
    $('.address:contains("Paris")').closest('.holder').addClass('invisible');
    e.preventDefault();
});

It is case sensitive though so if a div contains 'paris' instead of 'Paris' that won't get hidden.

See http://jsfiddle.net/2fEzS/19/

Upvotes: 0

Related Questions