please tell me I have a form within which one input and the "add" button ... everything works without a form, I click the add button and the element is added to the sheet! As soon as I create a form, when I press the button, I see that the element is somehow added and instantly disappears! here is my HTML:

<form id="zip"> <input type="text" id="candidate"/> <button type="submit" class="btnAdd" onclick="addItem()">Add</button> <ul id="places"></ul> </form> 

in ul id places these inputs should fit!

here's my js!

 function addItem(){ var ul = document.getElementById("places"); var candidate = document.getElementById("candidate"); var li = document.createElement("li"); var btn = document.createElement("button"); btn.onclick = function() { var ul = document.getElementById("places"); var candidate = document.getElementById("candidate"); var item = document.getElementById(candidate.value); ul.removeChild(item); ul.removeChild(btn); } var t = document.createTextNode("delete"); btn.appendChild(t); btn.className = "btnDelete"; document.body.appendChild(btn); li.setAttribute('id',candidate.value); li.appendChild(document.createTextNode(candidate.value)); ul.appendChild(li); ul.appendChild(btn); } var form = document.getElementById("zip"); form.reset(); 

Help me please!

    2 answers 2

    This happens because the default browser sends the form to the server, thereby reloading the page (or loads a new one). To cancel the browser action, there is a standard event.preventDefault () method.

    Use the following code.

    HTML:

     <button type="submit" class="btnAdd" onclick="addItem(event)">Add</button> 

    Javascript

     function addItem(event){ event.preventDefault(); // остальной код } 
    • Thanks It works! - German Varanytsya

    Why do you need a form?

     <button type="button" ... 

    By pressing the button with type="submit" , the standard form type="submit" takes place, and the page reloads. Change the button type or return false from the handler.

      ... onclick="addItem(); return false;" ... 
    • so on assignment you need ... - German Varanytsya