Vishnu Raj
Vishnu Raj

Reputation: 576

Getting clicked element from ul

I am populating a dynamic list using javascript. I have a onclick action where I need to get the clicked item from list. HTML is as:

 <div class="cate-map">
    <ul id="option1" onclick="doSelection()">

    </ul>

    </div>

I am populating list as:

jQuery.get(url, function(data) {
        for(i=0;i<data.length;i++){
            msg = "<li data-input="+data[i]+" class='selected'> <a href=#>"+data[i]+"</a></li>";
            document.querySelector('#option1').innerHTML +=  msg;
        }
    });

Onclick Listener is as:

function doSelection(){

    var id =$('#option1 li.selected').attr('data-input');
    alert(id);

}

Problem is that whenever I click li I am still getting the first element of the list. Not the one I clicked. Please help.

Upvotes: 3

Views: 627

Answers (2)

Bas Slagter
Bas Slagter

Reputation: 9929

This is because the selected class is on each element you are appending to the ul. You might want to add the onclick to each list item so you directly have the right context:

$('#option1 li').on('click', function(){
    alert($(this).data('input'));
});

This, of course, needs to be executed after the appending to the DOM has been finished. Alternatively you can bind the onclick on each element while you are appending:

jQuery.get(url, function(data) {
    var $list = $('#option1');

    for(i=0;i<data.length;i++){
        var $listItem = $('<li data-input=" + data[i] + " class='selected'> <a href=#>" + data[i] + "</a></li>');

        $listItem.on('click', function(){
            alert($(this).data('input'));
        });

        $list.append($listItem);
    }
});

Upvotes: 2

Satpal
Satpal

Reputation: 133403

I would recommend you to use Event Delegation using .on() delegated-events approach.

i.e.

$(document).on('event','selector',callback_function)

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

Example

$('#option1').on('click', 'li', function() {
  var id = $(this).data('input');
  alert(id);
});

$(document).ready(function() {
  var data = [1, 2, 3];
  for (var i = 0; i < data.length; i++) {
    var msg = "<li data-input=" + data[i] + " class='selected'> <a href=#>" + data[i] + "</a></li>";
    $('#option1').append(msg);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cate-map">
  <ul id="option1">
  </ul>
</div>

Upvotes: 3

Related Questions