There is a div with an array of checkboxes. How do I know, by clicking, which element I chose? That's the way I do

$(".cities_list").on('click', function() { var ids = $( ".select_cities :checked" ).map(function () { return this.value; }) console.log($ids) }); 

Thus, I get an id array, it does not work correctly, the first element is undefined, and the second is the selected id, or if it displays two id, then it is different then the same one.

All because we are looking around the div. Is there any other way to find out the id of the specifically "checked" element? Something similar mouseup - to intercept the one item that was checked, and not to go through the whole div ??

    2 answers 2

    It's not very clear what the ID is about, if, judging by the code, you are trying to get the value. What you need is to figure it out for yourself, but I’m showing how to get both the value and ID, and for every fire index of the element

     var chbx = $('.cities_list :checkbox').on('change', function() { console.log('Value: ' + $(this).val() + '\n' + 'ID: ' + $(this).attr('id') + '\n' + 'Index: ' + chbx.index(this)); }); 
     li { list-style: none; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="cities_list"> <ul> <li> <input type="checkbox" id="c1" value="100">100</li> <li> <input type="checkbox" id="c2" value="200">200</li> <li> <input type="checkbox" id="c3" value="300">300</li> </ul> </div> 

    PS If it is important that the element property is "checked = true", then do the appropriate check:

     if ($(this).prop('checked')) { // Чекбокс отмечен } 

      Hang the event on the checkbox itself:

       $(".cities_list input[type='checkbox']").on('change', function() { console.log($(this).val()); console.log($(this).attr('id')); });