Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
Adding elements to form dynamically with javascript

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!