-2

I have a simple list of contenteditable divs and I want to add new divs with a button and get the value of the contentediable like this:

HTML

<input type="button" id="addItem" value="Add item" />

<div class="itemContainer">
  <div class="item" id="item1" contenteditable="true">
    Item 1
  </div>
  <div class="item" id="item2" contenteditable="true">
    Item 2
  </div>
</div>

Javascript

$(function() {

  $("#addItem").click(function() {
    $(".itemContainer").append('<div class="item" id="item3" contenteditable="true">Item 3</div>');
  });

  $("[contenteditable]").blur(function() {
        console.log($(this).html());
  });

});

Fiddle

JsFiddle

The problem is that the console.log does not show the value of the contenteditable div after I pushed the button Add Item

The first 2 items are working properly.

How can I access the contenteditable in case of I have appended it to the DOM?

Any help is appreciated!

Thanks!

rwur
  • 237
  • 1
  • 6
  • 16
  • 4
    Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Zenoo Mar 26 '18 at 07:09
  • Yes, exactly! I had to add the `$(document).on(` function. http://jsfiddle.net/dyvgv39h/30/ – rwur Mar 26 '18 at 07:20
  • @rwur also div append code needs to be correct in a way so that it will not add `Item 3` repeatedly. You can check my answer for that – Alive to die - Anant Mar 26 '18 at 07:25

2 Answers2

1

1. You need to use jQuery event delegation

2. Also, you need to correct appending div code as it always pastes div with the repeated text of Item 3 every-time.

$(".itemContainer").on('blur',"[contenteditable]",function() {
  console.log($(this).html());
});

Working snippet:-

$(function() {

  $("#addItem").click(function() {
    $(".itemContainer").append(`<div class="item" id="item1" contenteditable="true">
    Item `+($('.item').length+1)+`
  </div>`);
  });

   $(".itemContainer").on('blur',"[contenteditable]",function() {
    console.log($(this).html());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="button" id="addItem" value="Add item" />

<div class="itemContainer">
  <div class="item" id="item1" contenteditable="true">
    Item 1
  </div>
  <div class="item" id="item2" contenteditable="true">
    Item 2
  </div>
</div>
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
1

You can use this script.

$(function() {
  $("#addItem").click(function() {
    $(".itemContainer").append('<div class="item" id="item3" contenteditable="true">Item 3</div>');
  });

  $(document).on("blur",".itemContainer [contenteditable]",function() {
        alert($(this).html());
  });

});

When you update the DOM dynamically you need to bind the event to newly updated Elements. Which can be done using $(document).on function.

Fiddle

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
SRK
  • 3,476
  • 1
  • 9
  • 23