tags:

views:

501

answers:

2

I'm pretty new to jQuery, so please forgive... I have a page with a long list of hyperlinks in an unordered list:

<div class="longlist">
<ul>
<li><a href="/firstitem.aspx" title="First Item">First Item</a></li>
<li><a href="/seconditem.aspx" title="Second Item">Second Item</a></li>
...
<li><a href="/lastitem.aspx" title="Last Item">Last Item</a></li>
</ul>
</div>

At the top of this page is a list of hyperlinks for the letters of the alphabet

<div class="alphabet">
<a href="#" title="A">A</a>
<a href="#" title="B">B</a>
<a href="#" title="C">C</a>
...
<a href="#" title="Z">Z</a>
<a href="#" title="All">ALL</a>
</div>

When a user clicks any of the links in the alphabetic index, I need to show only items in the long list that start with the selected letter. I also need to 'gray out' the alphabetic links if there is no item matching that letter in the long list (that way the user wont bother clicking an index that does not exist).

How can I do this using jQuery?

+4  A: 
$('myLetterList a').click(function(){
    var letter = $(this).attr('title');
    $('ul li').each(function(){
        var t = $(this).attr('title');
        if(letter != t.substring(0,1)){
            $(this).hide();
        }
    });
});

I'm sure there's a more jQuery-ish way to do it (particularly the .each() bit), but that should get you close to where you want to be.

inkedmn
I think I get what you're doing here. I probably will have to show all items first then hide the ones that do not match... or the other way round?
deverop
Correct - that code assumes that all items are visible and will hide the ones that don't start with the clicked letter. You might also want to add another bit that shows everything (if that fits with your design, of course).
inkedmn
+3  A: 
$(document).ready(function(){.

 $(".alphabet a").each(function(i){
  if ($(".longlist ul li a[title^="+$(this).text()+"]").length < 1){
   $(this).hide();
  }
 });

 $(".alphabet a").click(function(){
  var letter = $(this).text();
  if (letter == 'ALL'){
   $(".longlist ul li").show();
   return;
  }

  $(".longlist ul li").hide();
  $(".longlist ul li a[title^="+letter+"]").parent().show();

 });  
});

Seems to work for me :)

Michael Heap
ooh, didn't know about the [attribute^=] selectors
Jimmy
Thanks lvtrii, that looks very elegant! how about the bit to disable alphabetic links?
deverop
Ah sorry, didn't see that bit. You need to add:$(".alphabet a").each(function(i){ if ($(".longlist ul li a[title^="+$(this).text()+"]").length < 1){ $(this).hide(); } });
Michael Heap
That hides them as opposed to greying them out, but it's easy enough to change the action :)
Michael Heap
Oh my! I'll try that and report back....
deverop
excellent work lvtrii! The code works perfect. I only had to make minor modifications including changing **$(this).hide();** to **$(this).removeAttr("href");**
deverop