Reputation: 19
I have two input, textarea (name + comment) and Submit button. Onclick should post text from input and textarea. I use appendchild(), but need to call textarea. 1. How should I do it? 2. Button "Delete" remove all post, but I need delete just the last one. So how it is possible? Thank you for any tips.
There is the code:
<script type="text/javascript">
function append(form) {
if (form.input.value) {
var newItem = document.createElement("div");
newItem.appendChild(document.createTextNode(form.input.value));
document.getElementById("myDiv").appendChild(newItem);
}
}
function restore() {
var oneChild;
var mainObj = document.getElementById("myDiv");
while (mainObj.childNodes.length > 0) {
oneChild = mainObj.lastChild;
mainObj.removeChild(oneChild);
}
}
</script>
<form>Name:
<br>
<input type="text" name="input" />
<br />Comment:
<br>
<textarea type="text" name="textarea"></textarea>
<br />
<input type="button" value="Submit" onclick="append(this.form)" />
<input type="button" value="Delete" onclick="restore()" />
</form>
<div id="myDiv"></div>
Upvotes: 1
Views: 213
Reputation: 351
To solve your append issue:
function append(form) {
if (form.input.value) {
var newItem = document.createElement("div");
newItem.appendChild(document.createTextNode(form.input.value));
//add a line break and the text from textarea
newItem.appendChild(document.createElement("br"));
newItem.appendChild(document.createTextNode(form.textarea.value));
document.getElementById("myDiv").appendChild(newItem);
}
}
If you want to delete the last item only, you have to convert the while
loop to an if
condition:
function restore() {
var oneChild;
var mainObj = document.getElementById("myDiv");
if (mainObj.childNodes.length > 0) {
oneChild = mainObj.lastChild;
mainObj.removeChild(oneChild);
}
}
Upvotes: 0
Reputation: 25892
Problem is because you are saying while there are posts delete last one.
Put just this code in restore
. It will remove last child once.
function restore() {
var oneChild;
var mainObj = document.getElementById("myDiv");
oneChild = mainObj.lastChild;
mainObj.removeChild(oneChild);
}
Upvotes: 1