how to give a unique id to each input field created with button click

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • chijioke
    New Member
    • May 2017
    • 4

    how to give a unique id to each input field created with button click

    please i have a problem,i create new input field when a button is click,but i want each of the new create field to have a unique id,so i can use it for calculation in javascript.

    Code:
    function create(){
               
                var newinput = document.createElement('input');
                newinput.placeholder = "test1";
                newinput.id = 'test1'; 
                    document.getElementById("mytest").appendChild(newinput);
                }
    Last edited by Dormilich; May 4 '17, 01:17 PM. Reason: please use code tags
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    solution: don't use IDs for your calculation but classes. If you're having an unknown number of input fields, you can't base your calculation on IDs anyways.

    Comment

    • chijioke
      New Member
      • May 2017
      • 4

      #3
      but i don't know how to do that can you edit my code and fix it

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #4
        Code:
        function create()
        {
            var newinput = document.createElement('input');
            newinput.placeholder = "test1";
            document.getElementById("mytest").appendChild(newinput);
        }

        Comment

        • jmrker
          New Member
          • Dec 2012
          • 17

          #5
          As 'Dormilich' said, I would not recommend this approach for calculations, but it is not impossible to do and can be done like this...
          Code:
          <!DOCTYPE html>
          <html lang="en">
          <head>
          <meta charset="UTF-8" />
          <title> Create Inputs </title>
          </head>
          <body>
          <button onclick="countThem()">Count Them</button>
          <div id="mytest"></div>
          
          <script>
          function create(xx) {
            var newinput = document.createElement('input');
            newinput.placeholder = "test"+xx;
            newinput.id = 'inp'+xx;
            document.getElementById("mytest").appendChild(newinput);
          
            newinput = document.createElement('br');
            document.getElementById("mytest").appendChild(newinput);
           
          }
          
          function init() { for (var i=0; i<10; i++) { create(i); } }
          
          init();
          
          function countThem() {
            var sel = document.querySelectorAll('input');
            var str = '';
            for (var i=0; i<sel.length; i++) { str += sel[i].id+'\n'; }
            alert(sel.length+'\n\n'+str);
          }
          </script>
          
          </body>
          </html>

          Comment

          Working...