Declaring Javascript array within a function - javascript

Declaring an array within a function triggered by button causes the function to fail and not work as intended. What is the reason this happens? The "function C" block is having the problem.
I have also noticed that the ES6 syntax of "export ..." causes the entire thing to jam as well, it only accepts "module.export".
I am a total beginner, so I have no idea of what is going on.
This is my code:
<!-- Bootstrap CSS -->
<link href="resources/bootstrap.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="resources/custom2.css">
<link href="resources/TCJA's CSS.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
let TA = [0, 0, 0, 0]
function MF() {
TA = [0, document.getElementById("test1").value, document.getElementById("test2").value, document.getElementById("test3").value]
document.getElementById("shout1").innerHTML = TA[1]
document.getElementById("shout2").innerHTML = TA[2]
document.getElementById("shout3").innerHTML = document.getElementById("testCheck").checked
}
function C() {
var ACArray[0] = 2; //AttackerCard Array
var DCArray[0] = 1; //DefenderCard Array
var para = document.createElement("p");
var node = document.createTextNode("The attackers dealt " + document.getElementById("wand").value + " damage to the defenders.");
para.appendChild(node);
var element = document.getElementById("newElement");
element.appendChild(para);
}
</script>
</head>
<body>
<!-- Put code below -->
<br>
<label class="control-label">Tester Input</label>
<input class="form" id="test1">
<input class="form" id="test2">
<input class="form" id="test3">
<br>
<button id="doge" class="btn btn-primary" onclick="MF()"><h3>Result</h3></button>
<br>
<input id="testCheck" type="checkbox"> Check it?
<br>
<h2>Result:</h2>
<p id="shout1">Hello?</p>
<p id="shout2">Hello again?</p>
<p id="shout3">Hello a third time?</p>
<br>
<label class="control-label">Creator Input</label>
<input class="form" id="wand">
<button id="god" class="btn btn-success" onclick="C()"><h3>Create</h3></button>
<br>
<div id=newElement>
</div>
<button id="show">Show</button>
<!-- JQuery -->
<!-- End of body -->
</body>
</html>

What do you mean, by declaring var ACArray[0]=2;? Yes, it looks like declaring new array with first element equals 2, but, where is your array declaration?
The right way to do this: var ACArray = [2]; var DCArray = [1]; and so on.

Declare arrays Before assigning values into an array.
var ACArray = [];
var DCArray = [];
function C(){
ACArray[0] = 2;
DCArray[0] = 1;
}

The following syntax is incorrect:
var ACArray[0]=2; //AttackerCard Array
var DCArray[0]=1; //DefenderCard Array
The most convenient way to declare an array in JS is an Array literal like this:
var array = ['item1', 'item2'];
What we now have done is multiple steps in one. First we have created memory for an array using the var keyword and the array literal syntax.
Step 1:
var array = [];
Then we have initialized the array and put actual values inside the array like this:
Step 2
array[0] = 'item1';
array[1] = 'item2';
Important to understand is that you now can refer to all these elements in the following way:
console.log(array[0]); // logs item1
console.log(array[1]); // logs item2
And also be aware that the counting of the elements in the array starts with 0, not 1.

Related

how to make strings in a an array turn into variables in js

i wanted to turn this strings in this array to variables so i could assign them to html elements:
let array = ['varOne', 'varTwo', 'varThree']
let array[0] = document.getElementById('id')
You almost certainly don't want to do this, but if you did here is how:
const names = ['varOne', 'varTwo', 'varThree']
names.forEach((variableName) => {
window[variableName] = document.getElementById(variableName)
})
console.log(varOne)
console.log(varTwo)
console.log(varThree)
<html>
<body>
<div id='varOne' />
<div id='varTwo' />
<div id='varThree' />
</body>
</html>

How to remove an object from array using spilce?

I recently asked a question of (How to remove an element from array in javascript without making a new?).
b1 = document.getElementById('b1')
b2 = document.getElementById('b2')
myArray = [b1 , b2];
Now I have to use this array twice once i need choose random element from it and apply some properties on it and second i need to pop the element i have applied properties. Also its a long list of elements in array so i dont know their index numbers.
For better explanation
blocks = [document.getElementById("b1"),document.getElementById("b2"),document.getElementById("b3"),document.getElementById("b4"),document.getElementById("b5"),document.getElementById("b6"),document.getElementById("b7"),document.getElementById("b8"),document.getElementById("b9")]
//first use
function autoChance(){
const randomBlock = blocks[Math.floor(Math.random() * blocks.length)];
randomBlock.style.backgroundColor='blue';
}
//second use
function b1Click(){
b1.style.backgroundColor="red"
const index = blocks.indexOf('document.getElementById("b2")');
blocks.splice(index, 1);
console.log(blocks)
autoChance()
}
//If u see in console its removing the last item
.blocks{
width: 310px;
height: 304px;
overflow-wrap: normal;
background-color: aqua;
}
#b1,#b2,#b3,#b4,#b5,#b6,#b7,#b8,#b9{
width: 100px;
height: 100px;
position: relative;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="blocks">
<button id="b1" onclick="b1Click()"></button>
<button id="b2" onclick="b2Click()"></button>
<button id="b3" onclick="b3Click()"></button>
<button id="b4" onclick="b4Click()"></button>
<button id="b5" onclick="b5Click()"></button>
<button id="b6" onclick="b6Click()"></button>
<button id="b7" onclick="b7Click()"></button>
<button id="b8" onclick="b8Click()"></button>
<button id="b9" onclick="b9Click()"></button>
</div>
<script src="script.js"></script>
</body>
</html>
As I said in my comment on that other question, it doesn't matter what it is you're looking for, indexOf will find it if you pass the same thing into indexOf that's in the array; indexOf effectively does a === comparison.
Now, if you want to find the index of an object by checking its properties, or a string using a substring, or anything that isn't just a === comparison, you'd use findIndex with a callback (or find to find the object itself).
How can i remove them from array using the values...
The same way: splice with the index of the entry (if you want to keep the same array) or filter (if you want to create a new array).
Checkout this snippet. When you select elements using methods like getElementsByTagName, it may not return array. It might be an HTML collection or some object depending on the method you choose.
As you can see (in console), initially is an object. To change it to an array, see how I initialized elements, using [... ] Rest of the code is easy to understand. Let me know if you get stuck :)
var initially = document.getElementsByTagName('div')
console.log(typeof(initially));
var elements = [...initially];
console.log(elements);
var toSearch = document.querySelector('.four');
var ind = elements.indexOf(toSearch);
elements.splice(ind, 1);
console.log(elements);
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<div class="four"></div>
<div class="five"></div>
<div class="six"></div>
<div class="seven"></div>
I would get a random number based on the length of your element array and then splice the array based on that number and return the value from that splice. That value will, however, be in an array so I will need to return the first index of that array.
var myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
function removeElement() {
let randomIndex = randomize(myArray.length);
let randomValueArr = myArray.splice(randomIndex, 1);
let randomValue = randomValueArr[0];
console.log(randomValue);
return randomValue;
}
function randomize(max, min = 0) {
return Math.floor(Math.random() * max + min)
}
<button onclick="removeElement()">Click me to remove elements</button>

Quiz won’t continue

My quiz is getting caught and won’t pass through on to the next question when the right answer is given.
//loop through questions when right answer is given
function questFunc() {
"use strict";
//create array with my questions
var qArray = ["What is the answer to the sum 1 + 1?", "If I have two eggs and I drop one how many do I have left?", "What are the three primary colors?"];
var aArray = ["2", "1", "What are the three primary colors?"];
//create variables
var pageCounter = 1;
var qCounter = 0;
var aCounter = 0;
var theQuestions = document.getElementById("theQuestions");
var pageNum = document.getElementById("pageNum");
var theAnswer = document.getElementById("theAnswer").value;
if (qCounter < qArray.length) {
theQuestions.innerHTML = qArray[qCounter];
pageNum.innerHTML = pageCounter;
//not working - not allowing questions to move on when right answer is given.
if (theAnswer === aArray[aCounter]) {
qCounter++;
aCounter++;
pageCounter++;
}
} else if (qCounter >= qArray.length) {
theQuestions.innerHTML = "Well Done!";
pageNum.style.display = "none";
}
}
<div>
<h1 id="quizTitle">My JavaScript Quiz
</h1>
<p id="theQuestions">Click NEXT to start quiz..
</p>
<form id="" action="#" method="post">
<!-- Form Needs Columns -->
<div id="">
<label for="theAnswer"></label>
<input type="text" id="theAnswer" tabindex="1">
</div>
</form>
<span id="pageNum">
</span>
<button onclick="questFunc()">NEXT</button>
</div>
You're calling questFunc from the "Next" button, but all of your state is local to that function. So all of your state is recreated every time the function is called.
Instead, move the state that isn't specific to the function call out of the function. Since globals are a Bad Thing™, we'll do that by wrapping all our state (and the function) in a scoping function, and then use modern event handling to hook it up instead of onclick. (onxyz-attribute-style event handlers can only call global functions. It's one of the many reasons not to use them.)
So our scoping function, just to keep things contained, is:
(function() {
// Our code here
})();
...and our button is:
<button id="next-button">NEXT</button>
...and we hook it up using addEventListener:
document.getElementById("next-button").addEventListener("click", questFunc);
(See this answer if you need to support obsolete versions of IE.)
See the snippet for what state I moved out of the function, and see the comments for some other notes:
(function() {
"use strict";
var qArray = ["What is the answer to the sum 1 + 1?", "If I have two eggs and I drop one how many do I have left?", "What are the three primary colors?"];
var aArray = ["2", "1", "What are the three primary colors?"]; // Third answer looks like a copy-and-paste error
// We only need one counter, and let's start it at -1 because the first click
// starts the quiz
var counter = -1;
var theQuestions = document.getElementById("theQuestions");
var pageNum = document.getElementById("pageNum");
// Might as well get the answer field too
var theAnswer = document.getElementById("theAnswer");
// Hook up the button
document.getElementById("next-button").addEventListener("click", questFunc);
function questFunc() {
// Get their answer (if any)
var answer = theAnswer.value.trim(); // trim just to strip leading/trailing spaces
// If we're just starting the quiz or they answered correctly, show the next
if (counter == -1 || answer === aArray[counter]) {
counter++;
if (counter >= qArray.length) {
// Done with quiz
theQuestions.innerHTML = "Well Done!";
pageNum.style.display = "none";
} else {
// Show the now-current question
theQuestions.innerHTML = qArray[counter];
pageNum.innerHTML = (counter + 1);
}
// Always clear the answer
theAnswer.value = "";
} else {
// Incorrect answer, probably worth saying something here
}
}
})();
<div>
<h1 id="quizTitle">My JavaScript Quiz
</h1>
<p id="theQuestions">Click NEXT to start quiz..
</p>
<form id="" action="#" method="post">
<!-- Form Needs Columns -->
<div id="">
<label for="theAnswer"></label>
<input type="text" id="theAnswer" tabindex="1">
</div>
</form>
<span id="pageNum">
</span>
<button id="next-button">NEXT</button>
</div>
Your counters are within the function: "Double click next".
//loop through questions when right answer is given
var pageCounter = 1;
var qCounter = 0;
var aCounter = 0;
var qArray = ["What is the answer to the sum 1 + 1?","If I have two eggs and I drop one how many do I have left?","What are the three primary colors?"];
var aArray = ["2","1","What are the three primary colors?"];
function questFunc() {
var theQuestions = document.getElementById("theQuestions");
var pageNum = document.getElementById("pageNum");
var theAnswer = document.getElementById("theAnswer").value;
if (qCounter < qArray.length) {
theQuestions.innerHTML = qArray[qCounter];
pageNum.innerHTML = pageCounter;
//not working - not allowing questions to move on when right answer is given.
if (theAnswer === aArray[aCounter]) {
qCounter++;
aCounter++;
pageCounter++;
}
} else if (qCounter >= qArray.length) {
theQuestions.innerHTML = "Well Done!";
pageNum.style.display = "none";
}
}
<!DOCTYPE>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="quiz-css.css" />
<link rel="stylesheet" type="text/javascript" href="quiz-css.css" />
</head>
<body onload="">
<div>
<h1 id="quizTitle">My JavaScript Quiz
</h1>
<p id="theQuestions">Click NEXT to start quiz..
</p>
<form id="" action="#" method="post">
<!-- Form Needs Columns -->
<div id="">
<label for="theAnswer"></label>
<input type="text" id="theAnswer" tabindex="1">
</div>
</form>
<span id="pageNum">
</span>
<button onclick="questFunc()">NEXT</button>
</div>
<script src="quiz-js.js"></script>
</body>
</html>

Adding object to my array of objects using javascript functions

So i have a array of objects, I want to add new object into it. so I am using following code here is my code. I have seen other questions asked on the same topic but still I am not able to add my new object that i am fetching using jquery into my list. I am doing silly mistake please find it for me. Thanks
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<input placeholder="name" type="text" id="name"></br>
<input placeholder="rno" type="text" id="rollno"></br>
<input type="submit" value="Add Roll" id="add" >
<script type="text/javascript">
$(document).ready(function(){
console.log("loaded");
var list=[
{name:"sud",rno:1},
{name:"diya",rno:2},
{name:"sakshi",rno:3}
];
for(i=0;i<list.length;i++){
console.log("old list is"+list[i].rno+"\t"+
list[i].name);
};
$("#add").click(function(){
var rno = $("#rollno").val();
var name = $("#name").val();
//here i want to add rno and name to my list
for(i=0;i<list.length;i++){
console.log("new list is"+list[i].rno+"\t"+
list[i].name);
};
});
});
</script>
</body>
</html>
Array#push adds items to the end of an array. eg: arr.push("test");
$("#add").click(function(){
var rno = $("#rollno").val();
var name = $("#name").val();
// Use Array#push to add an item to an array.
// No need to use `new` when using the `{}` syntax for object creation.
list.push({name:"sudarshan",rno:"33"});
// Just a tip. You should use `var i = 0;` instead of `i = 0;` to keep the `i` variable out of the global scope.
for(var i = 0; i < list.length; i++){
console.log("new list is"+list[i].rno+"\t"+list[i].name);
};
});
to append to an array you can use push
list.push({name:"sudarshan",rno:"33"});
or just
list[list.length] = {name:"sudarshan",rno:"33"};
which is the same as above.

JavaScript getElementById returns null

I'm learning JavaScript and I'm wondering why something like:
document.getElementById('partofid'+variable+number) doesn't work?
Here are samples and JSfiddle link, I want "next" button to remove displayed item and show the next one.
HTML:
<div id="div-1"> 1 </div>
<div id="div-2" style="display: none"> 2 </div>
<div id="div-3" style="display: none"> 3 </div>
<div id="div-4" style="display: none"> 4 </div>
<a id="next" href="#">next</a>
JS:
var counter = 1;
var button = document.getElementById('next');
button.addEventListener("click",function(){
var currentDiv = document.getElementById('div-'+counter);
currentDiv.remove();
var nextDiv = document.getElementById('div-'+counter+1);
alert(nextDiv); // why does it return null
alert('div-'+counter+1); // while this doesn't?
nextQuestion.style.display = "block";
counter++;
},true);
Try using parseInt:
var nextDiv = document.getElementById('div-'+parseInt(counter+1,10));
The parseInt function converts its first argument to a string, parses it, and returns an integer.The second arguement is radix which is "base", as in a number system.
Demo
What's going on here is Javascript has some strange rules about types and the + operator.
string + anything means convert anything to string, then concatenate them together. So "foo" + "bar" == "foobar"... and "div" + 1 == "div1".
The the next step, addition is done left to right, so "div" + 1 + 1 goes to "div" + 1 == "div1".
"div1" + 1... remember, convert to string then put together, so we get "div1"+ 1 == "div11".
I would put parenthesis around your arithmetic. "div" + (1+1) would do the right hand side thing first, so (1+1) == 2 as you expect, then "div" + 2 == "div2", so that's what you expect.
As to the alert thing, your first one is looking at the result of the element lookup, and the second one is looking at the string itself. So the first is null because the element lookup didn't find anything.
This code results in string concatenation. E.g. if counter is 1, then you will get div-11
'div-'+counter+1
This is because addition is resolved from right to left.
Then you try to retrieve element with id div-11, but you don't have html element with such an id. That's why the function getElementById returns null.
To solve the problem first add counter to 1 and then join it with div, like this 'div-'+(counter+1)
Because counter+1 = 11 => id = div-11 is not exist. Try this:
var counter = 1;
var button = document.getElementById('next');
button.addEventListener("click",function(){
var currentDiv = document.getElementById('div-'+counter);
currentDiv.remove();
var nextDiv = document.getElementById('div-'+Number(counter+1));
alert(nextDiv); // why does it return null
alert('div-'+Number(counter+1)); // while this doesn't?
nextQuestion.style.display = "block";
counter++;
},true);
it does work and does exactly what you asked it to do but since you do not have a div-11 there is nothing found so the evaluation returns null.
if you want div-2 then simply use order of operations to sum the counter to the number:
Fiddle
Here is your answer:
<html>
<head>
<script>
function load()
{
var counter = 1;
var button = document.getElementById('next');
button.addEventListener("click",function(){
var currentDiv = document.getElementById('div-'+counter);
currentDiv.remove();
var nextDiv = document.getElementById('div-'+(counter+1));
//alert(nextDiv); // why does it return null
//alert('div-'+(counter+1)); // while this doesn't?
nextDiv.style.display = "block";
counter++;
},true);
}
</script>
</head>
<body onload="load()">
<div id="div-1"> 1 </div>
<div id="div-2" style="display: none"> 2 </div>
<div id="div-3" style="display: none"> 3 </div>
<div id="div-4" style="display: none"> 4 </div>
<a id="next" href="#">next</a>
</body>
<html>
To solve this kind of returning "null" values by getElementById("").
you can use script inside the body instead of head it will return the html element.
const m=document.getElementById('one')
const m1=document.getElementById('demo')
console.log(m1);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="demo">sample text</p>
<script src="script.js"></script>
</body>
</html>

Categories