Adding textbox on button click with javascript

前端 未结 2 885
时光说笑
时光说笑 2021-01-16 22:15

I\'m working on a web form with a textbox for pets and an \"add pet\" button. Each time the button is clicked, an additional textbox should be displayed below the original o

相关标签:
2条回答
  • 2021-01-16 22:40

    Something like this?

    <form name="myForm" id="myForm" onsubmit="return validateForm()">
        Pets: <br />
        <input type="text" id="pets" />
        <input type="button" id="addPet" value="Add Pet" />
        <br/>
    </form>
    


    document.getElementById("addPet").onclick = function() {
        var form = document.getElementById("myForm");
        var input = document.createElement("input");
        input.type = "text";
        var br = document.createElement("br");
        form.appendChild(input);
        form.appendChild(br);
    }
    

    Edit: I'd suggest using a table to style the input boxes, keep them in line. FIDDLE

    0 讨论(0)
  • 2021-01-16 22:43

    You could easily add elements to the DOM:

    function createPetField() {
      var input = document.createElement('input');
      input.type = 'text';
      input.name = 'pet[]';
      return input;
    }
    
    var form = document.getElementById('myForm');
    document.getElementById('addPet').addEventListener('click', function(e) {
      form.appendChild(createPetField());
    });
    
    0 讨论(0)
提交回复
热议问题