Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle a highlighted selected item in a group list

Tags:

I have this in using Bootstrap:

    <ul class="list-group">
        <li  class="list-group-item active">Cras justo odio</li>
        <li class="list-group-item">Dapibus ac facilisis in</li>
        <li class="list-group-item">Morbi leo risus</li>
        <li class="list-group-item">Porta ac consectetur ac</li>
        <li class="list-group-item">Vestibulum at eros</li>
        <li class="list-group-item">Cras justo odio</li>
        <li class="list-group-item">Dapibus ac facilisis in</li>
        <li class="list-group-item">Morbi leo risus</li>
        <li class="list-group-item">Porta ac consectetur ac</li>
        <li class="list-group-item">Vestibulum at eros</li>
    </ul>

The top row is selected.

I only ever want to show to the User 1 selected row.

I can raise an event when the User clicks on a row by adding a function to a Click-Event using Javascript.

I can then set that Row to be Active. but what happens is that the previous selected Row needs to be deselected.

What is the accepted way to do this?

How do I enumerate and access each row to change its Class settings?

Is there a better CSS way to do this?

ADDITIONAL All these methods work (thanks everyone) but if I have more than 1 option group on my page how can I explicitly remove the active highlighted row on the one I am using?

like image 717
Andrew Simpson Avatar asked Oct 03 '14 11:10

Andrew Simpson


1 Answers

Here we go buddy. I have made a JSfiddle for ya

demo

$(function(){
    console.log('ready');

    $('.list-group li').click(function(e) {
        e.preventDefault()

        $that = $(this);

        $that.parent().find('li').removeClass('active');
        $that.addClass('active');
    });
})

JSFiddle updated to have more than one Group

http://jsfiddle.net/mgjk3xk2/1/

like image 151
Sahan Avatar answered Sep 17 '22 17:09

Sahan