0

When I create new TASKs the "edit" (to save changes) and "delete" links stops working. What it wrong here?

I am using .on() but it doesn't work with new elements.

html:

<ul id="incomplete-tasks">
 <li>
      <input type="checkbox"><label>Pay Bills</label>
      <input type="text">
      <button class="edit">Edit</button>
      <button class="delete">Delete</button>
 </li>
 </ul>

jQuery:

 //Add new TASK
 $('#addButton').click(function(){
 $("#incomplete-tasks").append('<li><input type="checkbox"><label>' + $('#new-task').val() + '</label><input type="text"><button class="edit">Edit</button><button class="delete">Delete</button></li>')
 });

 //Show edit mode
 $("#incomplete-tasks").on("click", ".edit", function() {

 //show
 $(this).parent().toggleClass('editMode');

 //Add label value = edit field text
 var $label = $(this).children().find('label').text();
 $(this).children().find('input[type=text]').val($label);
 });

 //Save changes when "edit"is clicked again 
 $('.edit').on("click", function() {
 var value = $(this).parent().find('input[type=text]').val();
 $(this).parent().find('label').text(value);
 });

 //delete task 
 $('.delete').on("click", function() {
 $(this).parent().hide();
 });

FULL CODE - http://codepen.io/tsalexey544/pen/LEqbpV?editors=101

Alexey Tseitlin
  • 1,031
  • 4
  • 14
  • 33
  • 1
    I don't think that question has a answer to this. It may help but it's not the answer – Yerko Palma Mar 24 '15 at 12:16
  • this is not the same. I am using `.on()` but it doesn't work with new elements. – Alexey Tseitlin Mar 24 '15 at 12:16
  • Check [here](https://jsfiddle.net/yerkopalma/uomdrv5g/1/), i guess this is what you wanted. the problem was that you were trying to use the value of an input that had no value, so the label become empty, I just add the value for the hidden inputs. – Yerko Palma Mar 24 '15 at 12:29
  • @YerkoPalma what did you add? looks the same to me... – Alexey Tseitlin Mar 24 '15 at 12:43
  • I add a value to your inputs. In your addButton click handler, you were inserting inputs without value, and those were failing. So now when you click `edit` you wont erase your labels or inputs – Yerko Palma Mar 24 '15 at 12:44
  • @YerkoPalma I opened your code. Created new task. Clicked "edit". Added new text. Clicked "edit" again to save. Didn't save... – Alexey Tseitlin Mar 24 '15 at 12:57
  • You are right, I just fixed the toggle state, [this one](https://jsfiddle.net/yerkopalma/uomdrv5g/3/) is working on edit. Only the first `.on()` event handler work on dynamic added elements, so I added there the code to save changes. – Yerko Palma Mar 24 '15 at 13:08

0 Answers0