Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the checked checkboxes of a particular ul

I am creating a dynamic ul and trying to get the checked boxes of a particular ul only.

$(document).on("click", "input:checkbox[name=filter]:checked", function() {
  var flags = Array();
  $("input:checkbox[name=filter]:checked").each(function() {
    flags.push($(this).val());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="dropdown-list">
  <li><input type="checkbox" name="filter" value="form">Form</li>
  <li><input type="checkbox" name="filter" value="anonymise">Anonymise</li>
  <li><input type="checkbox" name="filter" value="priority">Priority</li>
  <li><input type="checkbox" name="filter" value="question">Question</li>
</ul>
<ul class="dropdown-list">
  <li><input type="checkbox" name="filter" value="form">Form</li>
  <li><input type="checkbox" name="filter" value="anonymise">Anonymise</li>
  <li><input type="checkbox" name="filter" value="priority">Priority</li>
  <li><input type="checkbox" name="filter" value="question">Question</li>
</ul>
<ul class="dropdown-list">
  <li><input type="checkbox" name="filter" value="form">Form</li>
  <li><input type="checkbox" name="filter" value="anonymise">Anonymise</li>
  <li><input type="checkbox" name="filter" value="priority">Priority</li>
  <li><input type="checkbox" name="filter" value="question">Question</li>
</ul>

all the three UL are identical, in this case how can i get the the all the checkboxes of a particular ul only.

this gives me all the selected checkboxes from all uls.

like image 635
ankur Avatar asked May 02 '17 11:05

ankur


1 Answers

I guess you want only the ul containing that clicked element. Try this:

$(document).on("click", "input:checkbox[name=filter]:checked", function(){
    var flags = Array();
    $("input:checkbox[name=filter]:checked", $(this).parents("ul").first()).each(function(){
        flags.push($(this).val());
    });
    console.log(flags);
});

The inner each function has a $(this).parents("ul").first() scope identifier before it. This will filter the inputs by the container of the clicked input.

like image 131
Taha Paksu Avatar answered Oct 22 '22 19:10

Taha Paksu