Skip to content Skip to sidebar Skip to footer

Jquery Add Class To This Clicked Element

I generate several rows with tasks. Now, each task can be marked as complete by clicking on a span. I do that with an ajax request. Here's the html: &

Solution 1:

try using following code, This is a prefered way jQuery

JS

$(".mark-as-complete").on("click", function(){
    $(this).addClass("completed);
});

$(".mark-as-complete").on("click", function(){ will trigger click function on span click

within that click function we are checking $(this) which will add class to clicked span.

Solution 2:

The context of element is lost in ajax call. you can use context option in ajax to set any elements context:

context:this,

Ajax call snippet:

$.ajax({
   type: "post",
   context:this,
   url: "assets/js/ajax/mark-as-incomplete.php",
   data: { 'task': task },
   success: function() {
       $(this).removeClass("completed-task");
   }
});

Solution 3:

You say you GENERATE the rows.

If you generate them on the client you need to delegate. Take the nearest static element to the generated rows, for example the table:

<table id="markTable">

then delegate like this:

$(function() {
  $("#markTable").on("click",".to-heal",function() {
    $(this).addClass("completed-task");
  });
  $("#markTable").on("click",".completed-task",function() {
    $(this).removeClass("completed-task");
  });
});

or just

$(function() {
  $("#markTable").on("click",".to-heal",function() {
    $(this).toggleClass("completed-task");
  });
});

UPDATE:

$(function() {
  $(".to-heal").on("click",function() {
    var task = $(this).attr("data-task");
    var completed = $(this).hasClass("completed-task");
    $.ajax({
      type: "post",
      context:this,
      url: "assets/js/ajax/mark-as-"+(completed?"in":"")+"complete.php",
      data: { 'task': task },
      success: function() {
        $(this).toggleClass("completed-task",!$(this).hasClass("completed-task"));
      }
    });
  });
});

or have ONE php that takes the parameter complete or incomplete

Solution 4:

Try to use this

$('span').click(function(){
    $(this).addClass("completed");
});

When you use an selector it search for the selected class or id and it will apply the property to all the existed selectors.

Post a Comment for "Jquery Add Class To This Clicked Element"