dkar dkar - 5 months ago 5x
Javascript Question

Get the ID of selected value of BootstrapCSS dropdown menu returns always the first option

I use BootstrapCSS and create a dropdown menu like this:

<div class="btn-group btn-group-sm">
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" id="modal-button-operators" type="button" data-toggle="dropdown" data-target="#">Operator
<span class="caret"></span></button>
<ul class="dropdown-menu dropdown-menu-operators" id="operator_list" style="height: auto; max-height: 200px; overflow-x: hidden;">
<li><a href="#" id="=">=</a></li>
<li><a href="#" id="&lt;&gt;">&lt;&gt;</a></li>
<li><a href="#" id="&gt;">&gt;</a></li>
<li><a href="#" id="&lt;">&lt;</a></li>
<li><a href="#" id="&gt;=">&gt;=</a></li>
<li><a href="#" id="&lt;=">&lt;=</a></li>
<li role="separator" class="divider"></li>
<li><a href="#" id=" LIKE ">LIKE</a></li>
<li><a href="#" id=" BETWEEN ">BETWEEN</a></li>

<div class="input-group-btn" id="button_query">
<a href="#" id= 'query_part' class="btn btn-primary btn-mg" data-toggle="modal" data-target="#myModal" title="Help" ><span class="glyphicon glyphicon-plus"></span></a>

Later, on button click, I want to get the ID of the selected value and store it in a variable. This is what I do:

$(document.body).on("click", "#button_query",function(e) {

operator_list = $("#operator_list li a").attr('id');


But this always gives me the ID of the first option of the dropdown list.
How can I get the ID of the selected value in dropdown menu?


You could consider adding a CSS class when a particular element was clicked that could be used to identify it when your button was pressed :

// When an element from your list is clicked, set it as "selected"
$("#operator_list li:not(.divider)").click(function(){
        // Ensure only the current one is selected
        $("#operator_list li:not(.divider)").removeClass('selected');

and then access the selected one through :

// Find the selected element and grab its id attribute
operator_list = $("#operator_list li.selected a").attr('id');


You can see a working example of this here and demonstrated below :

enter image description here