How to give unique ids to each child div created dynamically? - javascript

The function displays eight elements on click in dynamically created divs using the slice() method. How can I give a unique id to each div? Your suggestions would be of great help to me.
var words = [40];
var count = 0;
var x = "";
function nextElems() {
var newArray = words.slice(count, count + 8);
for (i = 0; i < newArray.length; i++) {
x += '<div class=box>' + newArray[i] + '</div>';
document.getElementById('container').innerHTML = x;
}
x = "";
count += 8;
}
I have tried this but it's not working:
var mainDiv = document.getElementById('container');
var first = mainDiv.getElementsByTagName('div')[0];
first.id = 'one';

You can do it right inside the for loop while it's iterating:
for (i = 0; i < newArray.length; i++)
{
x += '<div id="box-' + i + '"> class="box">' + newArray[i] + '</div>';
document.getElementById('container').innerHTML = x;
}

You can use assign an ID inside the text string.
Here are a couple of other things you can do to improve this code:
Move the getElementById outside the loop
use js methods instead of string concatenation
Something like this (untested):
// get the container
container = document.getElementById('container');
for (i = 0; i < newArray.length; i++)
{
// create a div
var div = document.createElement('div');
// add attributes
div.setAttribute("id", "box-" + i);
div.setAttribute("class", "box");
// create text node
var textnode = document.createTextNode("This is div #" + i);
// add text to div
div.appendChild(textnode);
// append to container
container.appendChild(div);
}

How about giving it the id when creating? Also put the class=box in quotations like so -> class="box".
And add the whole div construct only once after the for loop. Because right now you are basically overwriting the whole thing multiple times.
var words = [40];
var count = 0;
var x = "";
function nextElems() {
var newArray = words.slice(count, count + 8);
for (i = 0; i < newArray.length; i++)
{
// Change class and add custom id
x += '<div class="box" id="box-'+i+'">' + newArray[i] + '</div>';
}
document.getElementById('container').innerHTML = x; // Add divs after for loop
x = "";
count += 8;
}
Now each box has a unique id going from box-0, box-1, ... to box-n

Related

How to call two functions with the same event?

I want to display eight elements of first array in eight divs with class .box, and one element of second array in the center div with id center by clicking any div except the middle one with id center. The problem is the two functions named nextElems & arr are not called simultaneously. If one function is called, another does not work. I am able to call the function arr, but how to call the function nextElems simultaneously on the click of any div.
Your suggestions are always really great and helpful and I am much obliged.
<div id="container"> </div>
var words = [40];
// Showing 8 elements each time in different divs
var count = 0;
var x = "";
function nextElems() {
var newArray = words.slice(count, count + 8);
for (i = 0; i < newArray.length; i++)
{
x += '<div class=box>' + newArray[i] + '</div>';
document.getElementById('container').innerHTML = x;
}
x = "";
count += 8;
// Creating div in middle between fourth and fifth div
if (count <= 40) {
var center = document.querySelector('#div-3');
center.insertAdjacentHTML('afterend', '<div id="center"> </div>')
}
}
nextElems();
// Showing elements one at a time in order
var oppo = ["White", "Easy", "Soft", "Low", "Good"];
var x = "";
var count = 0;
function arr() {
if (count < oppo.length) {
x += '<div>' + oppo[count] + '</div>';
document.getElementById('center').innerHTML = x;
count++;
} else {
count = 0;
document.getElementById('center').innerHTML = "";
}
x = "";
}
arr();
$('.box').click(function() {
arr();
});
I have tried
$('.box').click(function() {
arr();
nextElems();
});
I have also tried it on the click of a button & with other jQuery
methods.
You need to declare variables inside a function scope.
Because now your code performed in the next order:
var count = 0;
var x = "";
nextElems();
var oppo = ["White", "Easy", "Soft", "Low", "Good"];
var x = "";
var count = 0;
..
someday later ...
..
arr(); //here you modify your global variables "x" and "count", so next function will use it with unpredictable values
nextElems();
so you need to declare it like
function nextElems() {
var count = 0;
var x = "";
...somecode
}
and then you can use
$('.box').click(function() {
arr();
nextElems();
});

Children loop html append into parent loop inserted div by javascript

The loop working but don't getting class as a selector from parent loop generated div...
var parentdiv = $(".pDiv");
for (i = 0; i < 3; i++) {
$(parentdiv).append("<label class="
addLabel ">" + i + "</label>"); // parent loop add
for (j = 0; j < 3; j++) {
$(".addLabel").append("<label class="
addLabel2 ">" + j + "</label>"); //children loop in parent class
}
}
First of all, your text has too many mistakes and it's hard to understand what exactly is the problem.
Secondly - your string in append() function is not concatenated properly as addLabel doesn't seem to be a variable. Try this:
$(parentdiv).append("<label class='addLabel"+ i +"'></label>") and
$(".addLabel").append("<label class='addLabel"+ j +"'></label>");
The problem solved the children loop :
//children loop start
for (var c = 0; c < checkBoxs.length; c++) {
// Things[i]
console.log(c);
var multiInputs = $("#myframe1").contents().find(".div2"); // iframe parent div
var putIntoParent = $(multiInputs).children(); // selector as parent children
var getMultiInput = multiInputs.selector;
//$(multiInputs).append('<lable><input type="checkbox"/>'+ checkBoxs[c].label +' </label>');
var node = document.createElement('span');
//var inputPlace = document.querySelector('.inputField_add');
console.log(multiInputs)
// $(multiInputs).on("load", function() {
$(putIntoParent).append('<lable><input type="checkbox"/>'+ checkBoxs[c].label +' </label>');
// });
}

I want to create div's in javascript so I do not have to sit there and make a hundred different divs

Okay so instead of typing out a hundred div tags in the hmtl I would like to generate them in javascript and have them show on the page. Here is what I have, but it will not work.
var arry = {};
for(var i = 0; i<100; i++){
arry[i] = i;
}
for each (var x in arry){
var div = document.createElement('div');
div.id = x;
document.getElementById('body').appendChild(div);
}
body is not an id, it is a tag. you need
document.getElementsByTagName('body')[0].appendChild(div);
This will create one hundred divs, each with a text node inside containing the number of the div.
var body = document.querySelector('body');
for(var x = 0; x < 100; x++) {
var div = document.createElement("div");
var text = document.createTextNode(x);
div.appendChild(text);
body.appendChild(div);
}
Alternatively you can do this:
var divs = '';
for (var i = 1; i <= 100; i++) {
divs += '<div id="id_' + i + '">Div ' + i + '</div>';
}
document.write(divs);

how to create more elements for the entered value in a textboxes in javascript?

I use for loop to create 3 textboxes with it's ids in javascript.. if I enter numbers on each text box I want to display same number of paragraphs element under each text box..
I have a problem: each textbox affected when i enter value in the other text boxes..
There is my codes:
for (i = 0; i < 3; i++) {
var tx = document.createElement('input');
tx.setAttribute('id', i);
tx.onblur = function () {
for (i = 0; i < 3; i++) {
var no = document.getElementById(i).value;
num = Number(no);
var d = document.getElementById('di' + i);
for (x = 0; x < num; x++) {
var tx1 = document.createElement('p');
tx1.innerHTML = " p" + x;
d.appendChild(tx1);
}
}
};
var div1 = document.createElement('div');
div1.setAttribute('id', "di" + i);
var div = document.getElementById('div1');
div.appendChild(tx);
div.appendChild(div1);
}
There are issues in code.
1)
var div = document.getElementById('div1');
div.appendChild(tx);
The code is asking for div with ID div1 which is never appended to DOM hence it returns null
thus null.appendChild(tx) fails.
Thanks
Added JSFiddle. If this is what you are trying to make..
http://jsfiddle.net/khm63wte/
just change your code, create a div on your document <div id="t"></div>, in your javascript create div first, then your input and append them to the document here is a working code
for (i = 0; i < 3; i++) {
var div1 = document.createElement('div');
div1.setAttribute('id', "di" + i);
document.getElementById('t').appendChild(div1)
var tx = document.createElement('input');
tx.setAttribute('id', i);
document.getElementById("di"+i).appendChild(tx);
tx.onblur = function () {
for (i = 0; i < 3; i++) {
var no = document.getElementById(i).value;
num = Number(no);
var d = document.getElementById('di' + i);
for (x = 0; x < num; x++) {
var tx1 = document.createElement('p');
tx1.innerHTML = " p" + x;
d.appendChild(tx1);
}
}
};
}

Changing radio buttons name using Javascript

I'm using a simple JS duplicate function to duplicate a div. Inside is form information with radio buttons, including one group called 'getOrRequest'. Each div represents a book and needs to have its own 'getOrRequest' value.
The name needs to be changed in order to make each duplicated group of radio buttons selectable without affecting every other radio button. What is the best way to change these values?
Here is how I'm duplicating the div, in case that is the issue.
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
bookInfo.appendChild(copyDiv);
I then have tried a couple methods of changing the name value. Like this:
bookInfo.copyDiv.getOrRequest_0.setAttribute("name", "'getOrRequest' + idNumber + '[]'");
bookInfo.copyDiv.getOrRequest_1.setAttribute("name", "'getOrRequest' + idNumber + '[]'");
As well as this:
bookInfo.copyDiv.getOrRequest_0.name = 'getOrRequest' + idNumber + '[]';
bookInfo.copyDiv.getOrRequest_1.name = 'getOrRequest' + idNumber + '[]';
getOrRequest_0 and getOrRequest_1 are the ID's of the input values, but I've tried it a few ways now and nothing seems to work. Thanks in advance!
EDIT: MORE INFO
Here is the specific code I'm using:
function addAnotherPost(){
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
var size = copyDiv.childNodes.length;
copyDiv.id = 'addListing' + idNumber;
for(var j = 0; j < size; j++){
if(copyDiv.childNodes[j].name === "getOrRequest[]"){
copyDiv.childNodes[j].name = "getOrRequest" + idNumber + "[]";
}
}
bookInfo.appendChild(copyDiv);
idNumber++;
}
And it just doesn't seem to work.. The divs are duplicating, but the name value is not changing.
You can try this - http://jsfiddle.net/ZKHF3/
<div id="bookInformation">
<div id="addListing">
<input type="radio" name="addListing0[]" />
<input type="radio" name="addListing0[]" />
</div>
</div>
<button id="button">Add Listing</button>
<script>
document.getElementById("button").addEventListener("click", AddListing, false);
var i = 1;
var bookInfo = document.getElementById('bookInformation');
function AddListing() {
var copyDiv = document.getElementById('addListing').cloneNode(true);
var size = copyDiv.childNodes.length;
copyDiv.id = "listing" + i;
for ( var j = 0; j < size; j++ ) {
if ( copyDiv.childNodes[j].nodeName.toLowerCase() == 'input' ) {
copyDiv.childNodes[j].name = "addListing" + i + "[]";
}
}
bookInfo.appendChild(copyDiv);
i++;
}
</script>
The trouble is you are looking for child nodes of the div, but the check boxes are not child nodes, they are descendant nodes. The nodes you are looking for are nested within a label. Update your code to look for all descendant inputs using copyDiv.getElementsByTagName("input"):
var idNumber = 0;
function addAnotherPost() {
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
copyDiv.id = 'addListing' + idNumber;
var inputs = copyDiv.getElementsByTagName("input");
for(var j = 0; j < inputs.length; j++){
if(inputs[j].name === "getOrRequest[]"){
inputs[j].name = "getOrRequest" + idNumber + "[]";
}
}
bookInfo.appendChild(copyDiv);
idNumber++;
}
http://jsfiddle.net/gilly3/U5nsa/

Categories

Resources