I am able to save user data from input field into paragraph, but I want to delete the contents of the paragraph with a click of button.
HTML:
<input type="text" id="name" placeholder="enter">
<br>
<button id="btn" onclick="fn()">click</button>
<div>
<p id="result"></p>
</div>
<button onclick="clear()">clear</button>
JAVASCRIPT:
function fn(){
var Name = document.getElementById('name').value;
document.getElementById('result').innerHTML += '<br>' + Name;
}
function clear(){
document.getElementById('result').innerHTML = "";
}
I think the problem here is the clear()
function name, it's not a reserved word, but it will invoke document.clear
in the first place, so try any other name for your function:
function fn(){
var Name = document.getElementById('name').value;
document.getElementById('result').innerHTML += '<br>' + Name;
}
function clearContent(){
document.getElementById('result').innerHTML = '';
}
<input type="text" id="name" placeholder="enter">
<br>
<button id="btn" onclick="fn()">click</button>
<div>
<p id="result"></p>
</div>
<button onclick="clearContent()">clear</button>
Update
To remove the inserted data one by one, you need to create an event listener for each created element, a simple implementation would be (remove element on click):
function fn() {
var Name = document.getElementById('name').value;
var paragraph = document.createElement('p');
paragraph.innerHTML = Name + ' (X)';
paragraph.onclick = function(el) {
el.target.remove();
return false;
};
document.getElementById('result').appendChild(paragraph);
}
function clearContent(){
document.getElementById('result').innerHTML = '';
}
<input type="text" id="name" placeholder="enter">
<br>
<button id="btn" onclick="fn()">click</button>
<div>
<p id="result"></p>
</div>
<button onclick="clearContent()">clear</button>
It seems clear
will call document.clear
. Change the function name to something else
let dom = document.getElementById('result');
function fn() {
var Name = document.getElementById('name').value;
dom.innerHTML += '<br>' + Name;
}
function clearVal() {
dom.innerHTML = "";
}
<input type="text" id="name" placeholder="enter">
<br>
<button id="btn" onclick="fn()">click</button>
<div>
<p id="result"></p>
</div>
<button onclick="clearVal()">clear</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With