venkatachalam
venkatachalam

Reputation: 102439

List selection in jQuery

I am using jQuery and my list has the following.

<div id="wrapper">
    <ul id="testnav">
        <li class="test1"><a href="/link">Heading</a>
            <ul>
                <li><a href="/link">Sub Heading</a></li>
                <li><a href="/link">Sub Heading</a></li>
                <li><a href="/link">Sub Heading</a></li>
            </ul>
        </li>
        <li class="test2"><a href="/link">Heading</a>
            <ul>
                <li><a href="/link">Sub Heading</a></li>
                <li><a href="/link">Sub Heading</a></li>
                <li><a href="/link">Sub Heading</a></li>
            </ul>
        </li>
        <li class="test3"><a href="/link">Heading</a>
            <ul>
                <li><a href="/link">Sub Heading</a></li>
                <li><a href="/link">Sub Heading</a></li>
                <li><a href="/link">Sub Heading</a></li>
            </ul>
        </li>
    </ul>
</div>

When I click the heading or sub heading I need that the corresponding text. I used the following, but it is not working.

$("li").bind("click", function(){
     alert( $(this).text());
});

What change should I make?

Upvotes: 0

Views: 326

Answers (3)

Oli
Oli

Reputation: 239998

Though neither of the other answers are incorrect, I'd do it like this:

$('#testnav a').click(function(ev){
    alert($(this).text())

    //if you need to stop the browser going to the link
    // (eg you're doing something else AJAXey):
    ev.preventDefault();
    ev.stopPropagation();
});

If the reason you were trying to attach to the lis directly is you want the whole thing to be "clickable", use CSS to resize your links:

#testnav a { display:block }

Depending on how you're doing it, you might need to play around making the link, li and/or ul float, and set widths.

Upvotes: 1

Andrew Hare
Andrew Hare

Reputation: 351758

You were very close - you need to bind the event to the anchor tag and make sure that you wrap your event binding in a $(document).ready function like so:

$(document).ready(function() {
    $("li a").bind("click", function() { alert( $(this).text()); })
});

Upvotes: 1

bchhun
bchhun

Reputation: 18484

 $("li a").bind("click", function(){
     alert( $(this).text());
 });

The li's text is actually an A link text. So you need to get that. that would only work for the children.

I'm not sure LIs have a click event but it would have worked if you'd use the html() function instead of text():

 $("li").bind("click", function(){
     alert( $(this).html() );
 });

Upvotes: 2

Related Questions