HTML:
<li><textarea></textarea></li><br><a id="newPoints"></a>
<input type="button" value="+ Add new point" onclick="newPoint();">
CSS (if you need it):
textarea {
font-family: Georgia, 'Times New Roman', Times, serif;
vertical-align: text-top;
width: 300px;
height: 60px;
resize: vertical;
padding: 10px;
}
And Javascript:
function newPoint() {
var a = document.getElementById("newPoints");
a.innerHTML += '<li><textarea placeholder="To delete this point, select this textbox and press the "Delete" button on your keyboard." onkeydown="if(event.keyCode == 46) { this.parentNode.nextSibling.parentNode.removeChild(this.parentNode.nextSibling); this.parentNode.parentNode.removeChild(this.parentNode); }"></textarea></li><br>';
}
To better visualise, here's a fiddle .
So basically, with the code above, I'm trying to make it such that when the user clicks on the button, a new <li>
(that comes with a <br>
after it) that contains a <textarea>
will get created. This new <li>
, <textarea>
and the following <br>
will be deleted when the user presses the Delete button on their keyboard while selecting the textarea.
The problem is that, when the user creates a new <li>
and types some text into its textarea, then create another <li>
, the text from the textarea of the previous <li>
will disappear.
How can I fix this?
Use CreateElement
and appendChild
to add the elements. I think what is happening is when you append to the innerHTML, it is overwriting everything in newPoints
.
function newPoint() {
var a = document.getElementById("newPoints");
var l = document.createElement("li");
l.innerHTML = '<textarea placeholder="To delete this point, select this textbox and press the "Delete" button on your keyboard." onkeydown="if(event.keyCode == 46) { this.parentNode.nextSibling.parentNode.removeChild(this.parentNode.nextSibling); this.parentNode.parentNode.removeChild(this.parentNode); }"></textarea>';
var b = document.createElement("br");
a.appendChild(l);
a.appendChild(b);
}
This might help:
function newPoint() {
var a = document.getElementById("newPoints");
var newcontent = document.createElement('li');
newcontent.innerHTML = "<textarea placeholder='To delete this point, select this textbox and press the "Delete" button on your keyboard.' onkeydown=\"if(event.keyCode == 46) { this.parentNode.parentNode.removeChild(this.parentNode);}\"></textarea>";
a.appendChild(newcontent);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.