Problem in the behavior of the button tag.
If type is not specified for it, the default is type="submit" . If the button is inside the form tag, then when you click on it in this case, the form will be sent and the page will be reloaded.
To solve the problem, you can use one of the following ways:
Move the button out of the form tag.
button2.onclick = function() { var newLi = document.createElement('li'); newLi.innerHTML = 'Привет, мир!'; list.appendChild(newLi); };
<input type="text" placeholder="to do" id="name"> <button id="button2">ДОБАВИТЬ</button> <ol id="list"> </ol>
set type attribute to button
button2.onclick = function() { var newLi = document.createElement('li'); newLi.innerHTML = 'Привет, мир!'; list.appendChild(newLi); };
<form> <input type="text" placeholder="to do" id="name"> <button type="button" id="button2">ДОБАВИТЬ</button> </form> <ol id="list"> </ol>
Cancel the default behavior by calling the preventDefault() method
button2.onclick = function(e) { e.preventDefault(); var newLi = document.createElement('li'); newLi.innerHTML = 'Привет, мир!'; list.appendChild(newLi); };
<form> <input type="text" placeholder="to do" id="name"> <button id="button2">ДОБАВИТЬ</button> </form> <ol id="list"> </ol>
return false;after the linelist.appendChild(newLi);- fonjeekay