Dhruv Gohil Dhruv Gohil - 6 months ago 20
jQuery Question

In Html Click On list (li) item not working with jquery

I am new to Html,jQuery coding.I want to change background color of item selected(clicked) of an li.
I have my code below :

#In HTML#

<div id="major" class="major-funds form-group"><strong>Major funds (above 1.0% market share)</strong>
<ul>
<li style="list-style: none; display:inline;padding-left:5px;" class="text-primary" ng-click="GetProducts(x.code)" ng-repeat="x in Major">{{x.code}}</li>
</ul>
</div>

# In controller#

$('#major li').click(function () {
$('li').removeClass('text-primary.selected');
$(this).addClass('text-primary.selected');
});


What am I doing wrong ? When I click on li item, It doesn't call that function.
IF I use this dynamic list it doesn't hit that function but if I use static list it does hit that function.How should I implement click function for dynamic list?

Answer

The click event is triggered (check with console.log function) but the action you execute are not defined properly.

$('li').removeClass('text-primary.selected');
$(this).addClass('text-primary.selected');

should be

$('li').removeClass('selected');
$(this).addClass('selected');

If your list is dynamically generated (not in the DOM on page load), the problem may come from the click function. In this case, just use :

$(document).on('click', '#major li', function () {
   $('li').removeClass('selected');
   $(this).addClass('selected');
});

where you can replace document by the container of your list. Per example :

$('#major').on('click', 'li', function () {
   $('li').removeClass('selected');
   $(this).addClass('selected');
});

Here is a JSfiddle with working example: https://jsfiddle.net/ztvdnh86/2/