Declare JScript variables by array and for loop - javascript

There is some part of my code that gives me headaches. I've missed something. I want to create, declare variables by array but it won't work. It works fine when I declare them manually (like am1=1; am2=2;...). But the problem is when I try the for loop and to create variables that way.
There is the FIDDLE of my problem
myhtml.html
1.Question:<br/>
<textarea name="question11" ></textarea><br/><div id="inner1"></div><button type="button" onClick="addmore1();">Add more</button>
<br/><br/>
2.Question:<br/>
<textarea name="question21" ></textarea><br/><div id="inner2"></div><button type="button" onClick="addmore2();">Add more</button>
myscript.js
var am = [];
for(var i=1; i<3; i++){
am[i] = 1;
}
function addmore1() {
am1++;
n=1;
var textarea = document.createElement("textarea");
textarea.name = "question" + n + am1;
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+n).appendChild(div);
}
function addmore2() {
am2++;
n=2;
var textarea = document.createElement("textarea");
textarea.name = "question" + n + am2;
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+n).appendChild(div);
}

Here is the fiddle with the fix for your problem.
If you look at the developer console (F12 in most browsers), you can see the error: am1 and am2 are undefined.
I guess what you meant to do is to refer to am[1] instead of am1. Althought the code is working after that change, there is a lot of room for improvement: you could reuse more code by having only one addmore function, etc . e.g.:
function addmore(index) {
am[index]++;
var textarea = document.createElement("textarea");
textarea.name = "question" + index + am[index];
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+index).appendChild(div);
}

if you are declaring them by array, why aren't you using them by array?
var am = [];
for(var i=1; i<3; i++){
am[i] = 1;
}
function addmore1() {
am[1]++;
n=1;
var textarea = document.createElement("textarea");
textarea.name = "question" + n + am[1];
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+n).appendChild(div);
}
function addmore2() {
am[2]++;
n=2;
var textarea = document.createElement("textarea");
textarea.name = "question" + n + am[2];
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+n).appendChild(div);
}
or am I missing something?

You must use .push() to add values to an array.
var am = [];
for(i=1; i<3; i++){
am.push(1);
}
Sorry if I didn't answer your question completely.

Related

How to change value of parent element to an element

I am trying to change the css property of the "node"-class by clicking on the div inside of it which got the class "expand".
When I click on the "expand" div inside the "note", I want to go to parent "note" for changing it size:
var text = document.getElementById("text");
var add = document.getElementById("add");
var notespace = document.getElementById("notespace");
var expand = document.getElementsByClassName("expand");
var notes = document.getElementsByClassName("note");
add.addEventListener("click", function () {
var textValue = text.value;
var p = document.createElement("p");
p.innerHTML = "<div class='note'>" + textValue +
"<br/><br/><div class='expand'> Expand </div></div>";
notespace.appendChild(p);
text.value = "";
for (var i = 0; i < expand.length; i++) {
expand[i].addEventListener("click", function () {
notes[i].style.size = "3000px";
})
}
})
You have to re-get the values of expand and notes, because after you add them to your html, the two variables expand and notes, dont know yet that you have added them and they don't contain them. ( you also have to removee the eventlistner otherwise you're gonna get a bugg at approximately twelve notes added :D because you will have too many eventListners on each element
var text = document.getElementById("text");
var add = document.getElementById("add");
var notespace = document.getElementById("notespace");
var expand = document.getElementsByClassName("expand");
var notes = document.getElementsByClassName("note");
add.addEventListener("click", function(){
var textValue = text.value;
var p = document.createElement("p");
p.innerHTML = "<div class='note'>" + textValue + "<br/><br/><div class='expand'> Expand </div></div>";
notespace.appendChild(p);
text.value = "";
for( var i = 0; i < expand.length; i++){
const note = notes[i];
expand[i].addEventListener("click", function() {
note.style.size = "3000px";
note.style.backgroundColor = "red";
});
}
})
#notespace {
width: 100%,
height: 100%,
background: grey,
}
<button type="button" id="add">add</button>
<input id="text"/>
<div id="notespace">
</div>
You can use the parentNode attribute :
for( var i = 0; i < expand.length; i++){
expand[i].addEventListener("click", function(){
this.parentNode.style.size = "3000px";
})
}
Or the closest() method :
for( var i = 0; i < expand.length; i++){
expand[i].addEventListener("click", function(){
this.closest(".note").style.size = "3000px";
})
}
Note that closest() is not supported on IE.

?JS How to exit from function?

I need to exit from mine.onclick = function so can anyone help me??
I'm new in js!
I tried to write the word game and I need to write the function, when I'm clicking on the button I need to move the button, but its not working 3th time
//creating div
var div = document.createElement('div');
div.innerHtml = '';
document.body.appendChild(div);
div.classList.add('main');
//creating divsec
var divsec = document.createElement('div');
divsec.innerHtml = '';
document.body.appendChild(divsec);
divsec.classList.add('submain');
//creating array for words
var arr = prompt("Write your word or sentance here and don't accept your apponent to see that!");
array = arr.split('');
array = array.sort();
console.log(array);
alert("Let's construct the word!");
var main = document.getElementsByClassName('main');
var divsec = document.getElementsByClassName('submain');
for(var i = 0; i < arr.length; i++){
var button = document.createElement('button');
divsec[0].appendChild(button);
button.innerHTML = array[i];
button.onclick = function(){
mainp = main[0].appendChild(this);
mainp.onclick = function (){
divsec[0].appendChild(this);
}
}
}
Is this the answer you're looking for?
//creating div
var div = document.createElement('div');
div.innerHtml = '';
document.body.appendChild(div);
div.classList.add('main');
//creating divsec
var divsec = document.createElement('div');
divsec.innerHtml = '';
document.body.appendChild(divsec);
divsec.classList.add('submain');
//creating array for words
var arr = prompt("Write your word or sentance here and don't accept your apponent to see that!");
array = arr.split('');
array = array.sort();
console.log(array);
alert("Let's construct the word!");
var main = document.getElementsByClassName('main');
var divsec = document.getElementsByClassName('submain');
for(var i = 0; i < arr.length; i++){
var button = document.createElement('button');
divsec[0].appendChild(button);
button.innerHTML = array[i];
button.onclick = function(){
if (this.parentNode.className === 'main') divsec[0].appendChild(this)
else main[0].appendChild(this);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.min.js"></script>
If it's not, please clarify your question and give an example of what is the desired effect on clicking a single button. I'm also not sure what you mean by exit the function. It seemed fine to me.
You stated that you need a button to move, but you didn't state how does it need to move.

Generate HTML with JavaScript not working?

I'm quite new to JavaScript so I don't understand what's not working.
The Code:
var postCount = 0;
function generatePost(title, time, text) {
var div = document.createElement("div");
div.className = "content";
div.id = "post_" + postCount;
document.getElementById("postcontainer").appendChild(div);
var h3 = document.createElement("h3");
div.id = "post_h3_" + postCount;
h3.innerHTML = title;
document.getElementById("post_" + postCount).appendChild(div);
var span = document.createElement("span");
document.getElementById("post_h3_" + postCount).appendChild(div);
span.innerHTML = time;
var paragraphs[] = text.split("||");
for (var p : paragraphs[] {
var paragraphCount = 0;
var h3 = document.createElement("h3");
document.getElementById("post_p_" + postCount + "_" + paragraphCount).appendChild(div);
paragraphCount++;
}
postCount++;
}
function loadPosts() {
generatePost("Testing Title", "I don't know", "This is || a paragraph");
}
I included it with:
<body onload="loadPosts()">
In the end, nothing shows up. Not even in the Inspector in my Browser. Is my Code even run? Did I forget an essential doStuffNow()?
Second: If I add a class to a div with JavaScript, do the CSS-Rules in the style.css append to it?
To answer the second part of your question, yes, the CSS styling that applies to a class will be added to an object that you add the same class to.
You have errors in your code. What editor do you use? You can also use browser console to check for errors in your page.
Check here:
var paragraphs = text.split("||");
for (var p in paragraphs) {
/*
*
* Where do you use your var p?
*
*/
var paragraphCount = 0;
var h3 = document.createElement("h3");
document.getElementById("post_p_" + postCount + "_" + paragraphCount).appendChild(div);
paragraphCount++;
}
Why don't you try with jQuery?

How can I add divs to an array dynamically?

I would like to create several divs with the same options like color, width, height, etc.
I would like to add all of these divs to an array, but I need to do this dynamically.
My current code:
var ArrayInfo = [];
do {
var InfoDiv = document.createElement('div');
InfoDiv.id = 'Info_Div';
InfoDiv.className = 'Info_Div';
InfoDiv.style.width = "100px";
InfoDiv.style.height = "30px";
InfoDiv.style.display = "inline-block";
ArrayInfo.push(InfoDiv);
}while(i < x);
x can be a very very large number.
Is this the right way to add div a to an array?
How can I write text into the elements of an array?
I tried this:
ArrayInfo[i].innerHTML = "something";
But it didn't work.
You never increment i, so your loop will never end.
Second, you never actually add any of the divs to the document -- creating them doesn't do that for you.
And as noted in the comments, you can't use the same id over and over.
var ArrayInfo = [];
var x = 10;
var ctr = document.getElementById('ctr');
for (var i = 0; i < x; ++i) {
var InfoDiv = document.createElement('div');
InfoDiv.id = 'Info_Div' + i;
InfoDiv.className = 'Info_Div';
InfoDiv.style.width = "100px";
InfoDiv.style.height = "30px";
InfoDiv.style.display = "inline-block";
ArrayInfo.push(InfoDiv);
ctr.appendChild(InfoDiv);
}
for (i = 0; i < x; ++i) {
ArrayInfo[i].innerHTML = "div " + i;
}
<div id=ctr></div>
I'd avoid using do...while. I'd also avoid creating a new div on every loop. Instantiate once, then clone (it's faster).
var InfoDiv = document.createElement('div');
InfoDiv.id = 'Info_Div';
InfoDiv.className = 'Info_Div';
InfoDiv.style.width = "100px";
InfoDiv.style.height = "30px";
InfoDiv.style.display = "inline-block";
var ArrayInfo = [];
for(var i = 0; i < x; i++) {
var div = InfoDiv.cloneNode(true);
div.id += i; // Add number to id
ArrayInfo.push(div);
}
IDs must be unique! Considering adding a number to the end of each Info_Div to uniquely identify it.
Also consider using a for loop instead of a do while loop.
The convention for JavaScript variables is lowerCamelCase. So we should fix that as well.
In your code, the divs were added to the array but not to the document. If you wanted to add them to the DOM, you would have to add document.body.appendChild.
Your code would look more like this.
var arrayInfo = [];
var x = 5; // Or whatever value it is
for (var i = 1; i < x; i++) {
var infoDiv = document.createElement('div');
infoDiv.id = 'Info_Div' + i;
infoDiv.className = 'Info_Div';
infoDiv.style.width = "100px";
infoDiv.style.height = "30px";
infoDiv.style.display = "inline-block";
arrayInfo.push(infoDiv);
arrayInfo[i].innerHTML = "div " + i;
document.body.appendChild(infoDiv);
}

javascript appenchild

for(var i=0; i<myJSONObject.model.length; i++){
var create_div = document.createElement('div');
create_div.id = 'model_id'+i;
create_div.innerHTML = myJSONObject.model[i].model_name;
var assign_innerHTML = create_div.innerHTML;
var create_anchor = document.createElement('a');
document.getElementById('models').appendChild(create_div);
document.getElementById(create_div.id).appendChild(create_anchor);
}
for ex the myJSONObject.model.length is 2
the output is like this
<div id = 'model_id0'>XXXXX<a> </a></div>
<div id = 'model_id1'>XXXXX<a> </a></div> */
but instead of above the output sholud be like this
<div id = model_id0> <a> xxxxxx</a></div>
<div id = model_id1> <a> xxxxxx</a></div>
how to append it inside of the innerhtml
any one plz reply !!!!
two suggestions:
1.) instead of assigning innerHTML to model_idx div assign the model name to its child a. and 2nd instead of appending it to DOM in every loop do it after completing the loop as to minimize frequent the DOM Update ie by:
objContainer = document.createElement('div');
for(....)
{
var create_div = document.createElement('div');
create_div.id = 'model_id'+i;
var create_anchor = document.createElement('a');
create_anchor.innerHTML = myJSONObject.model[i].model_name;
create_div.appendChild(create_anchor);
objContainer.appendChild(create_div);
}
document.getElementById('models').appendChild(objContainer);
I would go along the lines of:
var i = 0,
m = myJSONObject.model,
l = m.length,
models = document.getElementById("models");
for(; i < j; i++) {
var model = m[i];
var create_div = document.createElement("div");
create_div.id = "model_id" + i;
create_div.innerHTML = "<a>" + model.model_name + "</a>";
models.appendChild(create_div);
}
Unless you specifically need to do something to the anchor itself (other than set its innerHTML), there's no need to create a reference to an element for it. If you do need to do something specific to that anchor, then in that case have this, instead:
EDIT: As per your comment, you DO want to do something to the anchor, so go with this (now updated) option - assuming the anchor will always be a child of the div that has the ID you require. The reason "model_id" + i is being put in as a string is because that is exactly what is being passed into the HTML - the document has no clue what "i" is outside of javascript:
var i = 0,
m = myJSONObject.model,
l = m.length,
models = document.getElementById("models");
for(; i < j; i++) {
var model = m[i];
var create_div = document.createElement("div");
var create_anchor = document.createElement("a");
create_div.id = "model_id" + i;
create_anchor.innerHTML = model.model_name;
if(window.addEventListener) {
create_anchor.addEventListener("click", function() {
getModelData(1, this.parentNode.id);
}, false);
} else {
create_anchor.attachEvent("onclick", function() {
getModelData(1, this.parentNode.id);
});
}
create_div.appendChild(create_anchor);
models.appendChild(create_div);
}

Categories