krish krish - 7 months ago 27
Javascript Question

Get selected checkboxes from a drop down menu

I've the checkboxes inside a drop down menu. I've to get the checkboxes which are selected (checked)

Code:

<ul role="menu" class="dropdown-menu" id="comp">
<li><a href="#">
<input type="checkbox">
<span class="lbl"> Monday</span>
</a>
</li>
<li><a href="#">
<input type="checkbox">
<span class="lbl"> Tuesday</span>
</a>
</li>
<li><a href="#">
<input type="checkbox">
<span class="lbl"> Wednesday</span>
</a>
</li>
<li><a href="#">
<input type="checkbox">
<span class="lbl"> Thursday</span>
</a>
</li>
<li><a href="#">
<input type="checkbox">
<span class="lbl"> Friday</span>
</a>
</li>
</ul>
<input type="submit" class="btn btn-info" onclick="myFunction()" value="Submit">
<script type="text/javascript">
function myFunction()
{
/* Get selected check boxes here */
}
</script>


I'm sure it's a basic question. I'm new to javascript, trying to learn :)

Answer

Try it, it will return all selected checkbox values as you select any checkbox:

<ul role="menu" class="dropdown-menu" id="comp">
    <li><a href="#">
    <input name="chklist" onclick="get_selected_val()" value="monday" type="checkbox">
    <span class="lbl"> Monday</span>
    </a></li>
    <li><a href="#">
    <input name="chklist" onclick="get_selected_val()" value="tuesday" type="checkbox">
    <span class="lbl"> Tuesday</span>
    </a></li>
    <li><a href="#">
    <input name="chklist" value="wednesday" onclick="get_selected_val()" type="checkbox">
    <span class="lbl"> Wednesday</span>
    </a></li>
    <li><a href="#">
    <input name="chklist" onclick="get_selected_val()" value="thursday" type="checkbox">
    <span class="lbl"> Thursday</span>
    </a></li>
    <li><a href="#">
    <input name="chklist" onclick="get_selected_val()"  value="friday" type="checkbox">
    <span class="lbl"> Friday</span>
    </a></li>
</ul>


function get_selected_val() {
 $('input[name="chklist"]:checked').each(function() {
   console.log(this.value);
 });
}