Home > Back-end >  Why isn't clear button function isn't working?
Why isn't clear button function isn't working?

Time:11-07

The clear button isn't working to clear list-group history

//html 
<button class="btn btn-primary mb-3" 
   type="button" 
   id="clear-inputs"
   onclick="clearIt()">
    Clear history 
</button>
<form id="history"></form>
<div class="list-group" id="history"></div>
//javascript clear button function                           
function clearIt() {
  document.getElementById('history').value = "";
}

CodePudding user response:

You have two elements with the same id (the <form> and the <div>). Browsers will render this, but it is invalid html, as the id attribute is supposed to be unique to an element. getElementById() is going to grab the first element with the designated id.

The second problem with your html is that neither form or div elements have a value attribute, so there is nothing for your function to clear. It is unclear from your example which element is supposed to be cleared by your button. For the <div>, you could try setting document.getElementById('yourUniqueId').innerHtml = "". That will clear any html inside of the <div>.

CodePudding user response:

You don't need javascript for clear button, you can just use html for clear button only in form tag. Use for clear.

Here is a simple example: example

CodePudding user response:

  1. you have two 'history' id's - not a good practice

  2. use 'innerhtml' instead of value - will yield much better results. value is better for like inputs like a

CodePudding user response:

Make sure you provide a unique ID for your elements, 2 elements above has the same ID, also the function must be defined before calling it.

  • Always check your Console for logging/errors :)
  • Related