views:

85

answers:

3

I would like to accomplish the following with jquery :

When I click on this link

<a href="#">Cars</a>

I would like all divs like those

<div class="product">
    <div class="category">Cars</div>
</div>

to do something.

You get the idea, I have a menu with a list of categories, and a list of products, each containing a div with the category name, and I would like to make them hide/show.

+7  A: 

I am not sure if i fully understand your question, but if you want the div class="category" cars to appear when cars link is clicked, follow this:

$("#menu a").click(function() {
   var value = $(this).html();

   $.each($(".category"), function(i, item) {
     if ($(item).html() == value) {
         $(item).parent().hide();
     }

   });
});

if you want to hide the div just replace $(item).show(); with $(item).hide();

GerManson
Yes, thanks that's the idea, except I wanted to hide the parent div (the "product") not the "category" one. I managed to do that by doing $(item).parent().show(); instead of $(item).show();ps. I think there is a typo in your code, it should be if ($(item).html() == value) { instead of if ($(item).html == value) {
mike23
yes, it was a typo, thank you, I updated my answer with your final needs, good thing i helped you.. see you around! :) can you mark my answers as accepted?
GerManson
+2  A: 

Assuming:

<a href="#" class="highlight">Cars</a>

then:

$("a.highlight").click(function() {
  $("div.category").removeClass("category")
    .filter(":contains(" + $(this).text() + ")").addClass("highlight");
  return false;
});

What this does is add the category class to any category dvis that contain the text of the link. This can be modified to modify the parent product div if you want to do it that way too.

It works by first removing the class highlight from all category divs and then adding it to the ones that require it.

cletus
+1  A: 

DEMO: http://jsbin.com/ucewo3/11 SOURCE: http://jsbin.com/ucewo3/11/edit

    $('a').click( function(e) {
       var search_term = $.trim($(this).text()); //trim text
      $('.category').each(function() {  
      ($(this).text().search(new RegExp( search_term , 'i')) < 0 )//upper & lower
        ? $(this).parent().hide() : $(this).parent().show();  
       });  
    });

This keep the text inside the <a> tag and make a search into the <div class="category"> if the <a> text match with .category text it show the related .product content!

NOTE:

  1. the script match both Uppercase and Lowercase chars

    example match Cars as well as cars and CARS

  2. also match spaced text like <a> cars </a> as well as <a>cars</a> and <a>cars </a>

  3. match also tagged text like <div class="category"><span>cars</span></div>

​ ​

aSeptik
Interesting script ! Thanks for sharing
mike23