Othello
Othello

Reputation: 77

Changing a label using JavaScript click event handler

I am trying to remove a 'Pending' label and want to add a new 'Done' label. Please find below the code I have written so far. This code works but the Pending label is now along side the Done label. I thought the former can be removed.

$(document).on('click','.pending', function() {
    var li_node = $(this).parent();
    li_node.append('<span class="label success">Done!</span>');
    li_node.remove('<span class="label pending">Pending</span>');
    li_node.addClass('completed');
});

Screenshots of my work. Can I get rid of the Pending label and leave only the Done label?

This is the html code: I am following an online tutorial that seems to have been designed for you to have a seasoned JS coach with you;

<div id="container">
  <h1>Wish List</h1>
  <ol id="items">
    <!-- Items will be added here -->
  </ol>
  <span class="total"></span>
  <br/>
  <input type="text" id="item"/>
  <button id="add-to-list">Add to list</button>
</div>

enter image description here

Something tells me I should be starting a new topic for the addition to this question but that would mean duplicating all the previous code...let me know if I am breaking the rules please.

I don't have an idea how to write a jQuery selector that selects all the pending labels, using the .length property, in the JavaScript console. I am using all the previous codes and this is the screenshot of the list on my browser that I am working with. I need to get the number of pending labels and number of completed labels.

enter image description here

Upvotes: 0

Views: 902

Answers (3)

Mike
Mike

Reputation: 1683

Here is a working solution, I use a $ before the variable name when it is a jQuery object. If you remove the item after you get the selector for its parent element. then call remove on $(this) it works.

$(document).on('click', '.pending', function () {
    var $li_node = $(this).closest('li');
    $(this).remove();
    $li_node.append('<span class="label success">Done!</span>').addClass('completed');          
});

Upvotes: 0

Canta
Canta

Reputation: 1480

$(document).on('click','.pending', function() {
    var li_node = $(this).parent();
    li_node.append('<span class="label success">Done!</span>');
    li_node.children(".label.pending").remove();
    li_node.addClass('completed');
});

Upvotes: 1

Barmar
Barmar

Reputation: 781741

Instead of adding and removing things, just change the class and text of the label in place:

$(document).on('click','.pending', function() {
    var li_node = $(this).parent();
    li_node.children('.label.pending').removeClass("pending").addClass("success").text("Done!");
    li_node.addClass('completed');
});

Upvotes: 1

Related Questions