Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to iterate over a Bootstrap list?

I have a Twitter Bootstrap list with a variable number of elements (in fact there are two lists with draggable and droppable elements done with Sortable.js).

At some point, I want to iterate those lists elements in order to get a data atribute from each list entry. This is how my list looks like at HTML:

       <div class="panel-body">
            <ul id="main_list" class="list-group">
                <li id="opt1" href="#" class="list-group-item" data_value="1">Opt 1</li>
                <li id="opt2" href="#" class="list-group-item" data_value="2">Opt 2</li>
                <li id="opt3" href="#" class="list-group-item" data_value="3">Opt 3</li>
            </ul>
        </div>

Is this even possible to achieve, or am I thinking too object oriented? If not, how should I rethink this task?

like image 852
Roman Rdgz Avatar asked Dec 20 '25 20:12

Roman Rdgz


1 Answers

You can put your specific information like

<li id="opt3" href="#" class="list-group-item" data-value="3">Opt 3</li>

and get that easily with jquery:

$("#opt3").data("value")

But the semantic way to do that is with "-" instead of "_".


To iterate your list, you can do:

$("#main_list li").each(function(){
  var itemValue = $(this).data('id');
  var itemName = $(this).data('name');
  alert(itemValue+" - " +itemName);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
   <div class="panel-body">
            <ul id="main_list" class="list-group">
                <li id="opt1" href="#" class="list-group-item" data-name="customname1" data-id="1">Opt 1</li>
                <li id="opt2" href="#" class="list-group-item" data-name="customname2" data-id="2">Opt 2</li>
            </ul>
        </div>
like image 68
Thiago Avatar answered Dec 22 '25 11:12

Thiago



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!