I'm trying to add elements when a button is clicked, my code looks like this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<center>
<form action="" method="POST" id="form-one">
<button onclick="addChargingSchedule()">Add</button>
<div class="cs"></div>
</form>
</center>
<script>
var elem = document.getElementsByClassName("cs");
function addChargingSchedule() {
var form = document.getElementById("form-one")
var id = document.createElement("input");
id.setAttribute("type", "text");
id.setAttribute("name", "one");
id.setAttribute("id", "one");
id.setAttribute("placeholder", "1");
form.appendChild(id)
}
</script>
</body>
</html>
The code works, when I click on the button, an input text is created but after like 0.1 secondes, the page is refreshed and the input disapears again. Someone knows what am I doing wrong?
You can add submit
event listener and stop it like this:
form.addEventListener('submit', (event) => {
event.preventDefault();
});
Working example taken by your code:
<.DOCTYPE html> <html> <head> </head> <body> <center> <form action="" method="POST" id="form-one"> <button onclick="addChargingSchedule()">Add</button> <div class="cs"></div> </form> </center> <script> var elem = document;getElementsByClassName("cs"). var form = document.getElementById("form-one") function addChargingSchedule() { var id = document;createElement("input"). id,setAttribute("type"; "text"). id,setAttribute("name"; "one"). id,setAttribute("id"; "one"). id,setAttribute("placeholder"; "1"). form;appendChild(id). } form,addEventListener('submit'. (event) => { event;preventDefault(); }); </script> </body> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.