Variable Set to undefined - javascript

I am fairly new to Javascript and i ran into a problem when creating a chess game . I have already made the board, but when i tried incorporating JS code that would move these peices when i clicked on them, a problem arose. See i declared the variable "x" to hold the value of the chess peice value that had been clicked on when count=0 but when i tried it out, the code just outputs x as 'undefined'.What have i done wrong, any help would be appreciated :)
(below is a snippet of my JS code)
<div onclick="changeText(63)"id="63"class="black">♘</div>
<div onclick="changeText(64)"id="64"class="white">♖</div>
</div>
<script>
var count = 0;
var x;
function changeText(id) {
if (count > 1){
count = 0;
}
if(count=0){
x = document.getElementById(id).innerHTML;
document.getElementbyId(id).innerHTML="";
}
if(count=1){
document.getElementById(id).innerHTML=x;
}
count = count + 1;
}
</script>

The second and third if statements will not be evaluating the variable value - because rather than comparison (count=== 0) what happens there is a variable assignment (count = 0).
The if (count = 0) is evaluated to false, so, the variable x never gets a value.
On the other hand if (count = 1) is evaluated to true. So, the HTML element gets an undefined string. Your code should look like this:
...
if (count === 0){
x = document.getElementById(id).innerHTML;
document.getElementbyId(id).innerHTML="";
}
if( count === 1){
document.getElementById(id).innerHTML=x;
}
Reference: https://www.w3schools.com/js/js_comparisons.asp

You don't need to pass the id to that handler function if it's doing the same thing. If you want a function that changes the innerHTML of the thing that was clicked, try passing event to the handler, and then using event.target.innerHTML like this:
<div onclick="changeText(event)" class="black">♘</div>
<div onclick="changeText(event)" class="white">♖</div>
<script>
function changeText(event) {
if (event.target.innerHTML === 'x') {
event.target.innerHTML = 'y' // you can do anything here
} else {
event.target.innerHTML = 'x'
}
}
</script>

Related

How to change variable content getting the variable name from a data-attribute in a loop?

I have a loop that checks the content of an element's data-attribute and then uses this content to match it in a switch function. I want to simplify this code because the data-attribute value may vary in the next future and every time I have to add a case to the switch.
What I have now (this works fine):
var a = $('#el').attr('data-x'); // String
for (var i = 0; i <= 2; i++) {
switch (a) {
case "abc":
abc++; // variable initially set to 0
$('#abc').text(abc); // Overwrite the content with the new value
break;
case "dfg":
dfg++;
$('#dfg').text(dfg);
break;
[ ...Many cases like the ones listed here ]
}
if (i === 0) { a = $('#el').attr('data-x1')}
else if (i === 1) { a = $('#el').attr('data-x2');}
else if (i === 2) { a = $('#el').attr('data-x3');}
}
What I want to achieve is take the 'a' value, use the value taken as a var name and then work on the variable content.
EDIT: Mostly my need is a function non-depending from the cases, the way I've used in the code above it's ok for now but every 2 months I have to add another case to make it work. The question is: how can I change my code above to make it more "universal" and "elegant" in less line of code?
Something like:
var a = $('#el').attr('data-x');
for (var i = 0; i <= 2; i++) {
a++; // 'a' must be the name of the var, the name of the variable it's the same as $('#el').attr('data-x').
// So, 'a' var will change every time the function it's executed as in the switch version of the first block of code above (abc++ or dfg++).
$('#'+a).text(a);
if (i === 0) { a = $('#el').attr('data-x1')}
else if (i === 1) { a = $('#el').attr('data-x2');}
else if (i === 2) { a = $('#el').attr('data-x3');}
}
Here lies my problem: 'a' will be a string ('abc' for example), abc is a global var with the number needed to be incremented and placed in $('#abc'). Here we have for example:
abc = 0; (global var)
a = abc; (scoped var)
abc++; (abc === 1)
$('#abc').text(abc); (equivalent to $('#abc').text(1);)
So I need to call in the loop the 'a' value as the name of the global var, increment it, and then use 'a' as a jquery selector to text the value of the incremented global var inside it.
How can I do that?
If I understand what you need to do, you should try to use eval()
The eval() function evaluates JavaScript code represented as a string.
var a = $('#el').attr('data-x');
for (var i = 0; i <= 2; i++) {
eval(a + "++");
$('#'+a).text(eval(a));
if (i === 0) { a = $('#el').attr('data-x1')}
else if (i === 1) { a = $('#el').attr('data-x2');}
else if (i === 2) { a = $('#el').attr('data-x3');}
}

why is the if statement not working in js

window.addEventListener("keyup", addkey);
function addkey(){
var x = event.which || event.keyCode;
var wkey = 0;
var op = 0;
if(x == 87){
wkey += 1;
}
if(wkey == 1 && op == 0){
alert("your doing good!");
op = op + 1;
}
}
What im trying to get to happen here is getting the alert statement to run once and only once but i cant get it to work either way. I tried using a true or false numberical system (the op variable) but that dident work either. What i see happening is when the code runs and the keyup event fires the wkey variable updates once and stays 1 even know it should be going up a numeral each time the w key is pressed. Anyway i am making this code to go along with a tutorial for the game im making. Any and all suggestions i am open to.
This happens because you re-initialize op to 0 every time the function gets called. You can simply delcare op outside of addkey and it will work:
window.addEventListener("keyup", addkey);
var op = 0;
var wkey = 0;
function addkey(event){
var x = event.which || event.keyCode;
if(x == 87){
wkey += 1;
}
if(wkey == 1 && op == 0){
alert("your doing good!");
op += 1;
}
}
You'll also need to pull the declaration of wkey out of the function if you want to successfully count how many times it was pressed.
That's because you define wkey and op on each function run, you should define them out of the function, to make it work as expected.
Each time the function is called,
wkey gets set to 0,
and then 1 is added,
so it will always end up being equal to 1
Try defining wkey as 0 outside of the function.
Or having
if(wkey == null) var wkey = 0;
instead.
If you use this method op is unnecessary. (Unless of course you're using it's value elsewhere.)

How to create a simple variable alternator triggered by onclick?

This seems like a simple thing, my problem is that I learn things randomly, not in order.
I'm after a simple cycling/alternator where pushing something switches from one state to another eg. 1,2,1,2,1,etc...
So
I have my object to be clicked
<div onclick="alternateVar();">Click me</div>
Then I have the function/variable declaration/properties
I am not sure which variable setup I should choose I have shown three cases.
<script>
// check current value of variable
alert(mode);
// variable declaration
var mode = {value=1}; // method one
var mode = new Number(); // method two
var mode = 1; // method three
// alternate variable
function alternateVar() {
// attempt 1
if(mode.value == 1){
mode.value(2); // set new value to variable
}else {
mode.value(1);
}
// attempt 2
if(mode.value == 1){
var mode = 2; // overwrite? is it global?
}else {
var mode = 1;
}
}
</script>
Here's my fiddle. I just used a ternary operator! Is this what you needed?
var number = 1;
var button = document.getElementById("button");
button.onclick = alternateVar;
function alternateVar() {
number = number == 1 ? 2 : 1;
alert(number);
}

Store score in a variable after an event

Desirable result: After the user choose an answer, I want to modify score variable in:
score += 1 if the answer is right either not changing at all if the answer is wrong.
Current result: For every choice user is making, the score remains the same: 0.
First, I store the paragraph that will be changed in question_paragraph and the button that will be clicked by user in next_button. Also, I stored the value(I put the attribute value on every input using the array notation - 0 first, 1 second etc.) in user_answer.
var question_paragraph = document.getElementById('question');
var next_button = document.getElementById('next');
var i = 0;
var user_answer = getCheckedValue(document.getElementsByName('choice'));
var y = 0;
var score = 0;
The getCheckedValue function will return the value attribute of my input if exists.
function getCheckedValue(radioObj) {
var radioLength = radioObj.length;
for(var z = 0; z < radioLength; z++) {
if(radioObj[z].checked) {
return radioObj[z].value;
}
}
return "Error!";
}
Here is the problem. The function works fine, except the isolated area. allQuestion is my object where I stored the questions, the possible answers and the right answer, correctAnswer(I don't included it here but works correctly). I put a conditional statement to increase y and code>score with one if the allQuestions[y].correctAnswer is qual with the value of the user_choice.
function changeQuestion() {
//PROBLEM
if(allQuestions[y].correctAnswer == user_answer){
score += 1;
y++;
} else{y++;}
//PROBLEM
i = (i < allQuestions.length) ? (i + 1) : 0;
if (i == allQuestions.length) {
i = 0;
return question_paragraph.replaceChild(document.createTextNode(allQuestions[0].question), question_paragraph.firstChild);
}
var newNode = document.createTextNode(allQuestions[i].question);
console.log(score);
return question_paragraph.replaceChild(newNode, question_paragraph.firstChild);
}
Finnaly, I called the addHandler function.
function addHandler(name, type, handler){
if (name.addEventListener){
name.addEventListener(type, handler, false);
} else if (name.attachEvent){
name.attachEvent("on" + type, handler);
} else {
name["on" + type] = handler;
}
}
addHandler(next_button, 'click', changeQuestion);
Well, something just appears to be funny here so far. First of all, I don't see any initialization to the variable y. If y is a global variable that is retaining its value, then maybe there is an issue with your object: allQuestions{}. Could you provide the code for building your object allQuestions{}? Without it, I don't think that I could fully answer this question, but I believe that is where your problem lies.
Oops, this was supposed to be a comment, not an answer, sorry...

How do I correctly use an iteration value in JavaScript?

I am creating a 'simple' javaScript function which basically displays new information on the page when a user clicks next or previous.
The information is taken from an array and I want to use either i++ or i-- to call an element of the array.
Heres my JavaScript:
var titles = ["Dundalk", "Navan", "Drogheda", "Dublin"];
var i = 0;
function next()
{
i++;
if (i == titles.length)
{
i = 0;
}
var object = document.getElementById('tname');
object.innerHTML = titles[i];
}
function prev()
{
if (i == 0)
{
i = titles.length;
}
i--;
var object = document.getElementById('tname');
object.innerHTML = titles[i];
}
The problem is, when I run this code in my HTML page, I get an 'UNDEFINED' result. The JavaScript is not recognizing that i has been initialized as 0 in the beginning.
If i change titles[i] to titles[2], for example, the correct text is displayed in HTML.
What am I forgetting or how can I overcome this?
Thanks
The fact that you're seeing undefined indicates that you're accessing an array index which hasn't been set. Your code looks fine at a glance, so I would guess that there's some more code you're not showing which also uses i as a loop variable and leaves it set to a value > titles.length after the code above has run.

Categories