Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 549
user1450749 Avatar asked Oct 21 '25 03:10

user1450749


1 Answers

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') // ...
});
like image 76
undefined Avatar answered Oct 23 '25 17:10

undefined



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!