Reputation: 65
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.
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
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();
});
});
Upvotes: 1