Daniel Stakeley
Daniel Stakeley

Reputation: 65

jQuery - Added Input will not allow me to add text

After I create an input it will not allow me to add text. I am working on a project that allows the user to edit their text by clicking on the added text to make a changes.

CodePen example

    var $input = $("#change");
var $btn = $("#add");
var $btne = $("#edit");
var $content = $("#content");
$btne.hide();


$btn.click( function(){

 var typedInfo = document.getElementById("change").value;
 var item = $('<li></li>');
 item.append(typedInfo);
 $content.append(item);


 $content.on("click","li", function(){
  });

 item.click( function(){
     $btne.show();
     item.text(" ");
     var typeNew = $('<input type="text" id="newInput" value = "edit">')
     item.append(typeNew);
       $btne.click( function(){
        var editedInput = document.getElementById("newInput").value;
        item.text(editedInput);
        $btne.hide();
   });
 });


});

Upvotes: 3

Views: 51

Answers (2)

Robiseb
Robiseb

Reputation: 1606

As you may be know, when you click on an element, the click event is propagated to the top of the document.

So, when you click on a new input, the click is propagated to his parent <li> and the item.click(function(){...}) is called once again and the code is an other time executed and it rebuild all the current input area.

You have to stop the click event propagation to his parents.

typeNew.click( function(e){
  e.stopPropagation();
});

The full code

item.click(function(){
  $btne.show();
  item.text(" ");
  var typeNew = $('<input type="text" id="newInput" value = "edit">')
  item.append(typeNew);
  // Click on the new input
  typeNew.click( function(e){
    e.stopPropagation();
  });
  // Click on button
  $btne.click( function(){
    var editedInput = document.getElementById("newInput").value;
    item.text(editedInput);
    $btne.hide();
  });
});

stopPropagation documentation

Upvotes: 1

BrTkCa
BrTkCa

Reputation: 4783

item.click are in loop, always you click in item a new input is created. You can check for only one click with JQuery:

$("some_selector").one("click",function);

Upvotes: 1

Related Questions