Search code examples
jqueryeventsonclicktargettargeting

Can I have only one Index from a click event selected Item?


I have Problems with editing and deleting selected entries. i think it lies that i get only one index.

How i select things:

$("#liste").click(function selectList (event) {
        var target = $( event.target );
        if ( target.is( "li" ) ) {
            target.toggleClass('selected');
        }
    });

The Problem is here:

$('.selected').attr("index");

I only get the first Index from the selected Item, but i want to have all the indexes for every selected item. For Questionslook at this I have a Special Idea about an Edit function or feel free to ask!


Solution

  • attr() will, as you say, return the attribute from the first element in the matched set. If you want all of the index attributes from the selected objects, use map():

    var indices = $('.selected').map( 
      function() {
        return $(this).attr('index');
      }
    );
    

    var indices = $('.selected').map(function() {
      return $(this).attr('index');
    });
    
    console.log(indices);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="selected" index="one"></div>
    <div class="selected" index="two"></div>
    <div index="three"></div>
    <div class="selected" index="four"></div>
    <div index="five"></div>