Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear content with button

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 = "";
}
like image 264
pratteek shaurya Avatar asked Dec 05 '22 08:12

pratteek shaurya


2 Answers

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>
like image 164
Tamas Szoke Avatar answered Dec 07 '22 21:12

Tamas Szoke


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>
like image 30
brk Avatar answered Dec 07 '22 22:12

brk