List item gets cleared immediately after it is entered in HTML+JavaScript To-Do List

I am trying to create a simple HTML to-do list. Currently, the input works fine, it gets appended to the list but immediately gets removed. Is there something in my code that is causing it to do this?

const submitButton = document.getElementById('submitButton');
const li = document.createElement("li");

function newElement() {

  const inputValue = document.getElementById("myInput").value;
  const t = document.createTextNode(inputValue);
  li.appendChild(t);
  if (inputValue === '') {
    alert("You must write something!");
  } else {
    document.getElementById("myUL").appendChild(li);
  }
  document.getElementById("myInput").value = "";

  let submitButton = document.createElement("submitButton");
  // submitButton.className = "close";
  submitButton.appendChild(txt);
  li.appendChild(submitButton);
  console.log('function passed!')

}
<h1>To-Do List</h1>
<form>
  Add to your to-do list here: <input type="text" id="myInput">
  <button onclick="newElement()" id='submitButton'>Submit</button>
  <button id='clearButton'>Clear</button>
</form>

</br>
</br>

<ul id="myUL">
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>

1 answer

  • answered 2018-07-11 07:17 Munir Malik

    I resolved the issue by getting rid of the form tag entirely. Also, I made sure to put all the variables into the function itself (for the JavaScript bit)

    Here is my code:

    function addToList() {
    	const li = document.createElement("li");
    	const inputValue = document.getElementById("myInput").value;
    	const inputText = document.createTextNode(inputValue);	
     	li.appendChild(inputText);
    	if (inputValue === '') {
    	    alert("ERROR! INVALID INPUT");
    	} 
    	else {
    	    document.getElementById("myUL").appendChild(li);
    	}
    	document.getElementById("myInput").value = " ";
    
    	let submitButton = document.createElement("submitButton");
    	console.log('function passed!');
    	
    }
    <h1>To-Do List</h1>
    
    
    
    	<script src="toDoList.js"></script>
    
    
    		 Add to your list here: <input type="text" id="myInput">
    		 <button onclick="addToList()" id='submitButton'>SUBMIT</button>
    
    	</br>
    	</br>
    
    	<ul id="myUL">
    	</ul>