I have the following list that gets dynamically built and performs the same function as a select box would do.
<ul class="list-group" name="combobox1" id="combobox1">
<li class="list-group-item" value="6" />Option 1</li>
<li class="list-group-item" value="12" />Option 2</li>
<li class="list-group-item" value="15" />Option 3</li>
</ul>
When an item in the list is selected i user Jquery to append 'active' into the class to make 'list-group-item active'.
A user can select one or more list items from the list and click 'Show Details' which will give them details in a popup. This details popup is traggered by the onclick function in a button. My question is how do I use Jquery to get the values of one or more items in the list that a user has selected to pass via the onclick method?
onclick=showDetails(itemsvalues)
This returns one value, but what if there was more than one item selected?
onclick="showdetails($('#combobox1 li.active').val());
Thank you!
First of all use data-value for LI elements.
On LI click add some .active class
On button click get the data-value of the .active elements:
$("[data-value]").on("click", function(){
$(this).toggleClass("active");
});
$("#getValues").on("click", function(){
var values = $("[data-value].active").map(function(){
return $(this).data("value");
}).get();
alert( values );
});
.active{
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list-group" name="combobox1" id="combobox1">
<li class="list-group-item" data-value="6">Option 6</li>
<li class="list-group-item" data-value="12">Option 12</li>
<li class="list-group-item" data-value="15">Option 15</li>
</ul>
<button id="getValues">GET SELECTED VALUES</button>
To recap <li value="bla" />huh</li> is invalid markup, so remember to first learn HTML before jumping into JS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With