user4564807
user4564807

Reputation:

How to change the Class using jquery

MY Jquery Code:

   $('a#cusine1').on('click', function(){  
        $('div#product-list').html("LOADING..........").show();  

        $(".ccid").addClass("0");
        document.getElementById("ccid1").className="active2";     

    });  


        $('a#cusine2').on('click', function(){  
        $('div#product-list').html("LOADING..........").show();  
        $(".ccid").addClass("0");
        document.getElementById("ccid2").className="active2";

    });  


        $('a#cusine3').on('click', function(){  
        $('div#product-list').html("LOADING..........").show();  
        $(".ccid").addClass("");
        document.getElementById("ccid3").className="active2";

    });  

MY HTML CODE

      <li id="ccid1" class="ccid">
             <a href="#" id="cusine1"><i class="fa fa-ticket"></i>3 Star Hotel</a>                                  </li>
        <li id="ccid2" class="ccid">
              <a href="#" id="cusine2"><i class="fa fa-ticket"></i>3 Star Hotel</a>                            </li>
        <li id="ccid3" class="ccid">
   <a href="#" id= "cusine3"><i class="fa fa-ticket"></i>5 Star Hotel</a>
     </li>

OUTPUT NEEDED:

I need, when li id "ccid1" is clicked, the class "active2" should be added. other li should have only "ccid" class.

The number of li may change based on the PHP.

PROBLEM FOUND

In first time, when click li id "ccid1", the class "active2" is added. Then, if the li id "ccid2" clicked the class "active2" is added, but the li id "ccid1" class not set to "0".

Upvotes: 3

Views: 146

Answers (3)

TeamugDotNet
TeamugDotNet

Reputation: 1

I am making a bit of a guess as to what you need, and this code is untested:

$('li.ccid').on('click', function(){  
    $(".ccid").removeClass("active2");
    $(this).addClass("active2");
});

So when any li with a class of ccid is clicked:

  1. We ensure class "active2" is removed from all such li
  2. Class "active2" is added to the one which was clicked

Upvotes: 0

Roko C. Buljan
Roko C. Buljan

Reputation: 205987

As I've said in my comment, don't use classNames starting with / only - Number.

This is all you need:

$('.ccid a').on('click', function(){              // This targets all your links
    $('div#product-list').html("LOADING..........").show();  
    $(".active2").removeClass("active2");         // Remove existent active classes
    $(this).parent(".ccid").addClass("active2");  // Set active class 
});  

Upvotes: 1

DarioDF
DarioDF

Reputation: 301

A css class name cannot start with a number (CSS grammar) and any element can have more than a class, so if you need to remove a class (or set it to none) you should use removeClass

Upvotes: 3

Related Questions