By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,516 Members | 1,369 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,516 IT Pros & Developers. It's quick & easy.

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

P: 4
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.

Expand|Select|Wrap|Line Numbers
  1. function create(){
  2.  
  3.             var newinput = document.createElement('input');
  4.             newinput.placeholder = "test1";
  5.             newinput.id = 'test1'; 
  6.                 document.getElementById("mytest").appendChild(newinput);
  7.             }
May 4 '17 #1
Share this Question
Share on Google+
4 Replies


Dormilich
Expert Mod 5K+
P: 8,639
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.
May 4 '17 #2

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

Dormilich
Expert Mod 5K+
P: 8,639
Expand|Select|Wrap|Line Numbers
  1. function create()
  2. {
  3.     var newinput = document.createElement('input');
  4.     newinput.placeholder = "test1";
  5.     document.getElementById("mytest").appendChild(newinput);
  6. }
May 4 '17 #4

P: 17
As 'Dormilich' said, I would not recommend this approach for calculations, but it is not impossible to do and can be done like this...
Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title> Create Inputs </title>
  6. </head>
  7. <body>
  8. <button onclick="countThem()">Count Them</button>
  9. <div id="mytest"></div>
  10.  
  11. <script>
  12. function create(xx) {
  13.   var newinput = document.createElement('input');
  14.   newinput.placeholder = "test"+xx;
  15.   newinput.id = 'inp'+xx;
  16.   document.getElementById("mytest").appendChild(newinput);
  17.  
  18.   newinput = document.createElement('br');
  19.   document.getElementById("mytest").appendChild(newinput);
  20.  
  21. }
  22.  
  23. function init() { for (var i=0; i<10; i++) { create(i); } }
  24.  
  25. init();
  26.  
  27. function countThem() {
  28.   var sel = document.querySelectorAll('input');
  29.   var str = '';
  30.   for (var i=0; i<sel.length; i++) { str += sel[i].id+'\n'; }
  31.   alert(sel.length+'\n\n'+str);
  32. }
  33. </script>
  34.  
  35. </body>
  36. </html>
  37.  
Jun 4 '17 #5

Post your reply

Sign in to post your reply or Sign up for a free account.