the best practice for assigning an ID automatically - javascript

I have a page that contains a link like this:
new user
When the user clicks the link, I add a new input field to the page. I would like to assign an ID to that input field. I can do this using Javascript:
var num=0;
function add(){
num++;
var input = document.createElement('input');
input.setAttribute('ID',"input"+num);
}
This works; but my question is, is this the standard way, or is there a better way to do this, something that doesn't use num, JS or jQuery?

You don't need an ID on an input element. However you might be needing a name. If so, just use name = "input[]" - then on the server side you will get an array of values.

Since you're using jQuery:
$('<input id="input'+ num +'"/>').appendTo('#yourElement')

Just assign the id to the element:
var num=0;
function add(){
num++;
var input = document.createElement('input');
input.id = "input" + num;
}
Since you tagged your question with jQuery, you can also do this:
function add(){
var input = $('<input id="input' + num++ +'" />')
// do something with the input.
}
Or:
function add(){
var input = $('<input>', {id = "input" + num++});
// do something with the input.
}
Update:
You can't create DOM elements without javascript (jQuery is javascript).

var num=0;
function add(){
num++;
var input = document.createElement('input');
input.id = "input"+num;
}
random ID without num :
function add(){
var input = document.createElement('input');
input.id = 'input'+parseInt(Math.random()*1354243242);
}

Related

Javascript onClick doesn't work with button [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 6 years ago.
Pretty Straight forward. My button is not creating the input I need after the click event. I need the fields populated where the class "household" is. I cannot edit HTML only Javascript. Any ideas?
HTML:
<ol class="household"></ol>
<div>
<button class="add">add</button>
</div>
JS:
document.getElementsByClassName("add").onclick = function() {
createinput()
};
count = 0;
function createinput() {
field_area = document.getElementsByClassName('household')
var li = document.createElement("li");
var input = document.createElement("input");
input.id = 'field' + count;
input.name = 'field' + count;
input.type = "text"; //Type of field - can be any valid input type like text,file,checkbox etc.
li.appendChild(input);
field_area.appendChild(li);
//create the removal link
var removalLink = document.createElement('a');
removalLink.onclick = function() {
this.parentNode.parentNode.removeChild(this.parentNode)
}
var removalText = document.createTextNode('Remove Field');
removalLink.appendChild(removalText);
li.appendChild(removalLink);
count++
}
document.getElementsByClassName gives you object of all child elements which have all of the given class names . You will have to attach the event on each element by iterating over the array or by using index.
Here you can use document.querySelector for your example which returns the first Element matching with the selector.
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
document.querySelector(".add").onclick = function() {
createinput()
};
count = 0;
function createinput() {
field_area = document.querySelector('.household')
var li = document.createElement("li");
var input = document.createElement("input");
input.id = 'field' + count;
input.name = 'field' + count;
input.type = "text"; //Type of field - can be any valid input type like text,file,checkbox etc.
li.appendChild(input);
field_area.appendChild(li);
//create the removal link
var removalLink = document.createElement('a');
removalLink.onclick = function() {
this.parentNode.parentNode.removeChild(this.parentNode)
}
var removalText = document.createTextNode('Remove Field');
removalLink.appendChild(removalText);
li.appendChild(removalLink);
count++
}
<ol class="household"></ol>
<div>
<button class="add">add</button>
</div>
It should be document.getElementsByClassName("add")[0].onclick
As Document.getElementsByClassName():
Returns an array-like object of all child elements which have all of
the given class names. When called on the document object, the
complete document is searched, including the root node. You may also
call getElementsByClassName() on any element; it will return only
elements which are descendants of the specified root element with the
given class names.
document.getElementsByClassName("add")[0].onclick = function() {
createinput()
};
count = 0;
function createinput() {
field_area = document.getElementsByClassName('household')
var li = document.createElement("li");
var input = document.createElement("input");
input.id = 'field' + count;
input.name = 'field' + count;
input.type = "text"; //Type of field - can be any valid input type like text,file,checkbox etc.
li.appendChild(input);
field_area.appendChild(li);
//create the removal link
var removalLink = document.createElement('a');
removalLink.onclick = function() {
this.parentNode.parentNode.removeChild(this.parentNode)
}
var removalText = document.createTextNode('Remove Field');
removalLink.appendChild(removalText);
li.appendChild(removalLink);
count++
}
<div>
<button class="add">add</button>
</div>
x.getElementsByClassName()
getElementByClassName returns a collection.
x.onclick
onclick is meant for single elements and cannot be directly applied to a collection. Thats why your code is not working.
If you wanted to use a collection then a loop would work as suggested by one of the other answers.
I would have a think about the approach you want to take see this answer on .getElementsByClassName().

create html field based on js variable value

I have a property called results.row in JS. Using the value of that, I have to create textboxes in html. Suppose the value of results.row is 5,then I want to create 5 textboxes in html.
Also, the data to be shown on the textboxes is inside results.rows.item(i) . Is it possible to display?
HTML
<textbox name="Medicine Name" id="medicine"/>
JS
var rows = 5;
for (var i = 0; i < rows; i++)
{
var textbox = document.createElement('input');
textbox.type = 'text';
textbox.value = 'value here ' + i;
document.getElementsByName('medicine')[0].appendChild(textbox);
}

PHP text boxes dynamic ID generating

i would be very thankful if anyone could help me with this
i am trying to use php uploader plugin and upload multiple files.
i want to assign unique ids to the generating text box fields.
but whenever I am using a for loop to assign id , the text boxes won't show up
here is my code
var input = document.createElement('input');
input.value = task.FileName;
input.id = "textBox_";
for(var i = 0; i<0; i++){
input.id = "textBox_'.i.'";
}
document.body.appendChild(input);
}
the help will be appreciated ..
You are not appending the value of i properly. In js concatenation is done using + operator not using .
input.id = "textBox_"+i;
Place
document.body.appendChild(input);
inside the for loop like shown below as it has to generate input each time until loop ends.
for(var i = 0; i<0; i++)
{
input.id = "textBox_"+i;
document.body.appendChild(input);
}
Change input.id = "textBox_'.i.'"; to input.id = "textBox_"+i;
Concatenation in js is cone using + operator
So your code will be:
var input = document.createElement('input');
input.value = task.FileName;
input.id = "textBox_";
for(var i = 0; i<0; i++){//Condition of this loop is wrong in the sence it wont execute even once so fix it as your needs
input.id = "textBox_"+i;
document.body.appendChild(input);
}
}

javascript add two multipleevents on input field

I am trying to add two events on input field like onkeyup and onchange, the purpose is to avoid longpress of characters other than numbers..as the field is for zipcode. At present only one event is working either keypress/onchange.
I am adding my code for refrence any help would be appreciated.
function zipchange(obj, selector){
var code = obj.value;
var isnum = /^\d+$/.test(code);
if(!isnum)
obj.value="";
}//onchange
function autoZip(obj, selector){
var code = obj.value;
if(code.match(/\D/gi))
obj.value = code.replace(/\D/gi,'');
if(code.length>4 && code.indexOf('-')== -1){
var substr = code.substring(4);
substr=substr.replace(/\D/gi,'');
obj.value = code.substring(0,4)+'-'+substr;
}//onkeypress
//html
<input id="pincode" type="text" data-validate="validate[required]" name="address.pinCode" required="true" onkeyup="autoZip(this)" onchange="zipchange(this)" msg="Enter valid zip code" />
Answer:
function autoZip(obj, selector){
var code = obj.value;
if(code.match(/\D/gi))
obj.value = code.replace(/\D/gi,'');
if(code.length>4 && code.indexOf('-')== -1){
var substr = code.substring(4);
substr=substr.replace(/\D/gi,'');
var substr1 = code.substring(0,4);
obj.value = substr1+'-'+substr;
var isnum = /^\d+$/.test(substr1)
if(!isnum)
obj.value="";
}
Hi the above modified function did the trick..thanks for all the enlightned ones who helped me..
Well first of all onchange is triggered when you change the content of the text-box and when you loose focus from input type
Hence there is no use in using onchange event you have to implement your onchange logic in keyup event

Removing a text field using Javascript

I have the following code to add text fields when the function is called:
<span id="response"></span>
<script>
var qcountBox = 2;
var acountBox = 2;
var qboxName = 0;
var aboxName = 0;
function addInput()
{
var qboxName="question"+qcountBox;
var aboxName="answer"+acountBox;
if(qcountBox <=10 && acountBox <= 10)
{
document.getElementById('response').innerHTML+='<br/>Question '+qcountBox+': <input type="text" name="'+qboxName+'"/>';
document.getElementById('response').innerHTML+='<br/>Answer '+acountBox+': <input type="text" name="'+aboxName+'"/><br/>';
qcountBox ++;
acountBox ++;
}else
alert("No more than 10 questions allowed at this time.");
}
I also would like to be able to add a function to remove any new fields I have added. Any suggestions? Thanks
<script>
var qcountBox = 1;
var acountBox = 1;
var qboxName = 0;
var aboxName = 0;
function addInput()
{
var qboxName="question"+qcountBox;
var aboxName="answer"+acountBox;
if(qcountBox <=10 && acountBox <= 10)
{
document.getElementById('response').innerHTML+='<div id="'+qcountBox+'"><br/>Question '+qcountBox+': <input type="text" name="'+qboxName+'"/>';
document.getElementById('response').innerHTML+='<br/>Answer '+acountBox+': <input type="text" name="'+aboxName+'"/><br/></div>';
qcountBox ++;
acountBox ++;
}else
alert("No more than 10 questions allowed at this time.");
}
function removeInput(id)
{
document.getElementById(id).innerHTML = '';
}
You can remove any question that you added using the id of the question div (same as qboxName)
Surround each new piece of HTML in a span with a common class name. Then, find all the objects with that class name and remove them.
Add the span and class name to these:
document.getElementById('response').innerHTML+='<span class="added"> <br/>Question '+qcountBox+': <input type="text" name="'+qboxName+'"/></span>';
document.getElementById('response').innerHTML+='<span class="added"><br/>Answer '+acountBox+': <input type="text" name="'+aboxName+'"/><br/></span>';
Then, you can remove all the added spans like this:
var items = document.getElementsByClassName("added");
for (var i = 0; i < items.length; i++) {
items[i].parentNode.removeChild(items[i]);
}
Note: This is a generally better way to add your new HTML as it doesn't rewrite all previous HTML - it just adds new DOM objects:
var span = document.createElement("span");
span.className = "added";
span.innerHTML = '<br/>Question '+qcountBox+': <input type="text" name="'+qboxName+'"/><br/>Answer '+acountBox+': <input type="text" name="'+aboxName+'"/><br/>';
document.getElementById('response').appendChild(span);
You should actually create an input element in javascript and append it to your container through appendChild instead of using innerHTML +=.
You should also set an ID for those fields, not just a name. But it can be the same as theirs names.
Like this
var input = document.createElement("input");
input.type = "text";
input.name = input.id = qboxName;
document.getElementById("response").appendChild(input);
And then, you know, do the same for the other input field you need.
I know you need a text label for the boxes, or whatever, just do the same process to insert a span tag before them.
Also, I don't see a reason for those two counting variables. Instead of qcountBox and acountBox it's totally possible to have only one single counting variable. Maybe I'm wrong but shouldn't you increase this counting before setting the boxes names?
As for removing it, you can use the removeChild method, then, decrease your counting variable. like this:
function removeInput()
{
var qboxName = "question" + count;
var aboxName = "answer" + count;
document.getElementById("response").removeChild(document.getElementById(aboxName));
document.getElementById("response").removeChild(document.getElementById(aboxName));
count--;
}
Maybe if you're going to insert other elements together with these fields, like span tags for labels etc, it would be better to wrap them all up in a div or something, then simply do a removeChild to this container div only.

Categories