Hello, how can I insert text in an input and when I enter this text, it is displayed in a div, but if I insert another text, the old one is not deleted, only if I delete it myself.
what I want to do exactly is like the label field of this page, but instead of saving it in the input, save it in a div and be able to delete it, I attach an image
With this code I write everything before pressing enter.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Incluye texto con jQuery</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function (){
$('#campo').on('keyup', function(){
var valor = $('#campo').val();
$('#reflejar').text(valor);
//$('#campo').val("Hola mundo");
});
});
</script>
</head>
<body>
<input type="text" id="campo">
<div id="reflejar"></div>
</body>
</html>
You will need to create them
HTMLElement
dynamically.I include an example without using
JQuery
. You can do the translation, if you want.Let's go by parts.
For each event
keypress
in theinput
, I check if the key pressed is theenter
, which has the number as its code13
(functionenterPressed
). In that case, I'll add aHTMLElement
new one to the container.I don't directly modify the text inside the container. Keeping elements separate helps to have more concrete control over each of them, as well as the styles.
The function
addElement
creates adiv
, sets it asinnerHTML
the text ofinput
, and adds it to the container.Additionally, I also dynamically create a button and subscribe to it
click
so I can delete the element.Optionally, the style classes are added to the created elements and I store all the user inputs in an in-memory array.
Actually, with that array nothing is done, right now. From the same array you could also delete the elements. It occurs to me to save an object with the element, for example
In this way we can rescue it both by index and by the text and then delete it both from
container
and from the array.I hope it has helped.
Any questions tell me.