Targeting <li> inside another <li> - data id to enter field on click

I think this is quite simple, but after trying many different things, I hope you can help me.

I have a simple menu structure and when I press "li" I want the data id value to be passed to the input field. I can get this to work fine, but I am having problems with basic "li'es". Because they are "surrounded" by the "main" "li" and therefore the data id from that "li" will be selected, even though it is not the one I am pressing.

See an example here: http://jsfiddle.net/g35banrp/1/

It works great if you click for example Production, Technique or Option1, but if you click country or dealer if you select Sales. I understand why it does this but doesn't seem to fix it.

I've tried using the .closest selector but it doesn't seem to help in any way. Any hints, pointers or links are greatly appreciated :)

Regards, Peter

Script:

$('li.document').on('click',function(){var content= $(this).attr("data-id")$('#test').val(content);});

      

+3


source to share


2 answers


You are looking for the method .stopPropagation()

: http://jsfiddle.net/g35banrp/2/

$('li.document').on('click', function (e) {
    e.stopPropagation();
    var content = $(this).attr("data-id")
    $('#test').val(content);
});

      



https://api.jquery.com/event.stoppropagation/ prevents bubbles from appearing in parent / child relationship.

+3


source


You want an exact target for your click, so pass the event and use event.target

to get the correct one li

.



$('li.document').on('click',function(event){
    var content = $(event.target).attr("data-id")
    $('#test').val(content);
});

      

+1


source







All Articles