if...else if...else statement not working as intended [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm fairly new to Javascript and I'm trying to achieve something extremely simple but it seems impossible (at least the way I want it). Basically, I've got a HTML file with an image that I want to change to a different one every time I click on a button. I've got 4 images in total and the initial image in the HTML file is "1.jpg". The problem is, I can only change the initial "1.jpg" to "2.jpg" and any further attempts to change "2.jpg" to "3.jpg" and so on fail.
Here's the code
function changepicture() {
var a = ["1.jpg" , "2.jpg" , "3.jpg" , "4.jpg"];
if (document.getElementById('img1').src=a[0])
{
document.getElementById('img1').src=a[1];
}
else if (document.getElementById('img1').src=a[1])
{
document.getElementById('img1').src=a[2];
}
else if (document.getElementById('img1').src=a[2])
{
document.getElementById('img1').src=a[3];
}
else
{
document.getElementById('img1').src=a[0];
}
}
The thing is, I can get it to work if I change the code to:
var i=0;
function changepicture() {
i++;
if (i>3) { i=0; }
var a = ["1.jpg" , "2.jpg" , "3.jpg" , "4.jpg"];
document.getElementById('img1').src=a[i];
}
But, in spite of having a working alternative, I'm still not satisfied as I am convinced the first method should also work.

It appears you're using = where you mean to use == or ===.
Edit: To be more clear, I mean in the parenthesis of the if statements themselves, like this:
if (document.getElementById('img1').src == a[0]) {
Double edit: I believe I found another issue. It's in the logic of the if statements:
document.getElementById('img1').src
Doesn't just equal what's in the html, like '1.jpg'. It returns the WHOLE url. Check out the console logs on this quick fiddle I made: http://jsfiddle.net/71t4axv0/1/
First, it'll complain about that image not really being an image. Then you can see the actual logic: 'http://fiddle.jshell.net/_display/2.jpg', of course, does not equal 2.jpg

if (document.getElementById('img1').src=a[0]) {
document.getElementById('img1').src=a[1];
}
This particular statement of must have == instead of =.

The = / == typo that has been addressed by the other answers. Here, I'll address the second version of the function, where it seems you attempted to implement it as a loop. You'd have to write it like this:
function changepicture() {
var a = ["1.jpg" , "2.jpg" , "3.jpg" , "4.jpg"];
var element = document.getElementById('img1');
var src = element.src.split('/').pop(); // get filename
for(var i = 0; i < 3; i++) {
if (src == a[i]) {
element.src = a[i + 1];
return; // stop evaluating now
}
}
element.src = a[0];
}
Note: as a work around to the issue that holl pointed out about using the .src property, I use .src.split('/').pop() to get just the filename. This works, but an alternate solution would be to use the full paths in your array instead.
If you prefer, you can simplify this by using the indexOf method and the % operator:
function changepicture() {
var a = ["1.jpg" , "2.jpg" , "3.jpg" , "4.jpg"];
var element = document.getElementById('img1');
var curIndex = a.indexOf(element.src.split('/').pop());
element.src = a[(curIndex + 1) % a.length];
}
Here's a modified snippet that demonstrates the basic behavior (just with text, not images):
function changepicture() {
var a = ["1.jpg" , "2.jpg" , "3.jpg" , "4.jpg"];
var element = document.getElementById('demo');
var curIndex = a.indexOf(element.innerText);
element.innerText = a[(curIndex + 1) % a.length];
}
#demo { width: 40px; height: 40px; border: 1px solid #000; margin: 5px }
<div id="demo">1.jpg</div>
<button onclick="changepicture()">change</button>

Related

Proper syntax for nested if statements within for loops in Javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Pardon my stupid question, but I just started learning Javascript and HTML by myself yesterday. I am trying to replicate a type-racer sort of game, and can't seem to be able to complete a for loop due to an if statement within it.
See the following:
<script>
var current = document.getElementById('currentWord');
function inputMatch(){
var input = document.getElementById('inputfield').value;
if(input.length > current.innerHTML.length){
current.className = "currently-wrong";
}
else{
for (var i = 0; i < input.length; i++){
if(input[i] != current.innerHTMl[i]){
current.className = "currently-wrong";
};
else{
current.className = "currently-correct";
}
};
}
}
</script>
The word that is supposed to be typed is named current
I am fetching the user input in a variable named input
I want to iterate through the input to see if it matches with current. If it matches so far, I wish to change the class to "currently-correct" and otherwise, I wish to change it to "currently-wrong".
I don't know any way of debugging other than placing an alert(i) within the for loop.
When I do so, there is no output. if I remove the else statement and keep the alert(i), the only output are distinct "0"s, which implies that i remains at 0 and does not iterate.
If I remove the if statement AND the else statement, the output is correct as I type in the input.
Namely, if I type
"a" -> 0
"p" -> 0, 1
"p" -> 0, 1, 2
"l" -> 0,1,2,3
"e" -> 0, 1, 2, 3, 4
This is the expected output/alert, but only works if I remove the if statement. Any suggestions on debugging this?
I recommend you to use let and const instead of var to reduce unwanted side-effects. Also there should not be a ; after the if brackets.
And when the if statement matches, meaning that the input is wrong, there is no need for further checking (in fact it will also result in errors if you only type one wrong letter in the middle). So just hop out of the loop by using break;
const current = document.getElementById('currentWord');
function inputMatch(){
const input = document.getElementById('inputfield').value;
if(input.length > current.innerHTML.length){
current.className = "currently-wrong";
}
else{
for (var i = 0; i < input.length; i++){
if(input[i] != current.innerHTML[i]) {
current.className = "currently-wrong";
break;
}
else {
current.className = "currently-correct";
}
};
}
}
.currently-wrong {
background-color: red;
}
.currently-correct {
background-color: green;
}
<div id="currentWord">apple</div>
<input id="inputfield" onkeyup="inputMatch()"/>
You could however also write it in a prettier way like so:
const current = document.getElementById('currentWord');
const inputField = document.getElementById('inputfield');
const inputMatch = () => {
const input = inputField.value;
const matches = current.innerHTML.startsWith(input);
current.className = matches ? "currently-correct" : "currently-wrong";
}
.currently-wrong {
background-color: red;
}
.currently-correct {
background-color: green;
}
<div id="currentWord">apple</div>
<input id="inputfield" onkeyup="inputMatch()"/>

Javascript: Expected Identifier [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am creating an HTML document and using javascript to create an image element.
Here is my code (create is already defined):
create=document.createElement("img");
create.src = 'data/1.png';
create.alt = 'image1';
create.style.magin = '1px';
eval("create.id = 'image" + count + "'");
create.class = 'block'; // line that breaks the code
document.body.appendChild(create);
I don't know what's going wrong here, but it's probably something obvious. Does anyone have any ideas?
Here's your code working with the variable count defined, an example image and the correct way to add a class to the element:
var count = 1;
create=document.createElement("img");
create.src = 'http://via.placeholder.com/350x150'; // 'data/1.png';
create.alt = 'image1';
create.style.magin = '1px';
eval("create.id = 'image" + count + "'");
create.classList.add('block');
document.body.appendChild(create);
As no necessity for eval and you can use classList for add a class.
for(var count = 1; count < 10; count++){
create=document.createElement("img");
create.src = 'data/1.png';
create.alt = 'image' + count;
create.style.magin = '1px';
create.id = 'image' + count;
create.classList.add('block');
document.body.appendChild(create);
}
You also can use create.style.display = 'block'; if you want just add a style.
More examples how set attributes and styles here

createElement within for loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I want to make an element 50 times within a for loop. My code is below:
function pGenerate() {
for (i, i <= 50; i++;) {
var newP = document.createElement("p");
var pText = document.createTextNode("sample paragraph");
newP.appendChild(pText);
var contentSection = document.getElementById("content");
document.body.insertBefore(newP, contentSection);
}
}
The expected result is that it generates 50 <p> tags with "sample content inside of them. The actual result is well...nothing. https://jsfiddle.net/2L8reked/1/
My thought process behind the code I wrote this code is as follows: I basically have a loop set to cycle 50 times. for each cycle, I want to create a p tag, along with create a text node with the content "sample paragraph." In the next step, I grab the div by it's id, #content, and I then attempt to populate the area using insertBefore.
My error here seems to be how I use insertBefore. Looking this up on MDN, it's definition is "inserts the specified node before the reference node as a child of the current node." https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore
With that definition in mind - I'm using this with the understanding as of now that I'm inserting (or attempting to) the p tags as a child of #content. Should I be using a different method? Am I misunderstanding how this works?
I also tried an innerHTML approach, seen here: https://jsfiddle.net/0e1ej9sk/1/
which method is best suited for what I'm trying to do?
In the first example what is the flaw behind my logic of the use of insertBefore?
You have 3 syntax errors.
Change i, in for loop to 1=1; then remove the last ; where i++; to i++
function pGenerate() {
for (i=1; i <= 50; i++) {
var newP = document.createElement("p");
var pText = document.createTextNode("sample paragraph");
newP.appendChild(pText);
var contentSection = document.getElementById("content");
document.body.insertBefore(newP, contentSection);
}
}
window.onload = function() {
pGenerate();
}
<div id="content"></div>
You need to initialize i at 1, and properly separate all parts of the for statement with semi-colons, like this:
function pGenerate() {
for (var i = 1; i <= 50; i++) {
var newP = document.createElement("p");
var pText = document.createTextNode("sample paragraph (i=" + i + ")");
newP.appendChild(pText);
var contentSection = document.getElementById("content");
document.body.insertBefore(newP, contentSection);
}
}
pGenerate();
<div id="content"></div>
you can do this
function pGenerate() {
for (i=1; i <= 50; i++) {
var newP = document.createElement("p");
var pText = document.createTextNode("sample paragraph");
newP.appendChild(pText);
var contentSection = document.getElementById("content");
document.body.insertBefore(newP, contentSection);
}
}
document.ready(pGenerate);

How do i randomly display my questions so its now always the same? (JavaScript)

<script type="text/javascript">
var questions = [
['http://i.imgur.com/k0fBtYP.png','0'],
['http://i.imgur.com/1PwDTVY.png','1'],
['http://i.imgur.com/QKE9UFA.png','2'],
['http://i.imgur.com/XEGhtgB.png','3'],
['http://i.imgur.com/QhnCkAp.png','4'],
['http://i.imgur.com/JoL8tco.png','5'],
['http://i.imgur.com/tcZNls4.png','6'],
['http://i.imgur.com/V9DQI0p.png','7'],
['http://i.imgur.com/39ePipM.png','8'],
['http://i.imgur.com/16yFeMy.png','9'],
['http://i.imgur.com/UUo2yNc.png','10'],
['http://i.imgur.com/5sza6Wm.png','11'],
['http://i.imgur.com/ygPZBdY.png','12'],
['http://i.imgur.com/SwJYBRR.png','13'],
['http://i.imgur.com/wNdpJBX.png','14'],
['http://i.imgur.com/wUS7pDs.png','15'],
['http://i.imgur.com/OEI6ZYX.png','16']
];
var qNo = 0;
var correct = 0;
var cnt = 0;
function NextQuestion(response) {
if ((qNo < questions.length) && (response == questions[qNo][1])) { correct++; }
document.getElementById('score').innerHTML
= 'Your score is '+correct+'/'+(cnt+1);
qNo++;
if (qNo < questions.length) { document.getElementById('Pic').src = questions[qNo][0]; cnt++; }
else { alert('Quiz is done'); }
}
onload = function() {
document.getElementById('Pic').src = questions[0][0];
}
</script>
Okay so basically I have 17 questions and 17 answers that are listed using the numbers 0-16, what I want to do is randomize the order in which the pictures are shown so that you cant just find a pattern and not answer it right, also and I cant figure this out, I want to make it so that after each question is answered a green Correct or a Red incorrect shows up depending on If you got the previous question right can anyone help?
sorry, presently i have to rush so i won't be able to give you a code but I can give you the steps you need to follow.
Shuffle the array How to randomize (shuffle) a JavaScript array
Write a simple loop that cycles through the array
Take a look at this. Once you get a value between 0 and 16, store it as i, then display the question that corresponds with i. After you get the answer, remove that question and answer from the array by questions.splice(i, i+1); and answers.splice(i, i+1); Now repeat this for each question and eventually, the questions and answers array will reach a length of 0. This means that the user answered all of the questions.

Does my javascript contain repetitive code that can be reduced? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I feel like there is too much repetitive code going on here. All I am doing is doing a basic regex match for a string in the URL. If a match is found, I find an li with a class (.index, .grid, .type) and add the active class. This is just for my main nav in an attempt to make it some what dynamic. However, I feel like there is a more efficient way to code this. Any help is greatly appreciated.
$( document ).ready(function() {
var myLocation = window.location;
var convertURL = new String(myLocation);
var index = /index/i;
var grid = /grid/i;
var type = /type/i;
var urlIndex = convertURL.match(index);
var urlGrid = convertURL.match(grid);
var urlType = convertURL.match(type);
if(urlIndex) {
$('.index').addClass('active');
}else if(urlGrid) {
$('.grid').addClass('active');
}else if(urlType) {
$('.type').addClass('active');
}
});
$(function(){
["index", "grid", "type"].forEach(function(term){
if(new RegExp(term, "i").test(location.href))
$("." + term).addClass("active");
});
});
$(document).ready(function () {
// use single var per function, good for minimizing and other stuff
var
i,
// new string literal, not String object
convertURL = '' + window.location,
// the array of strings keeps only the difference from the repetitive code
classes = ['index', 'grid', 'type'],
// using functions with proper arguments reduces repetitivness
matches = function (regex) {
return convertURL.match(new RegExp(regex, 'i'));
}
// var
;
// always use += instead of ++ -> makes for clear intention
for (i = 0; i < classes.length; i += 1) {
if (matches(classes[i])) {
// returning out of this function stops iteration
return $('.' + classes[i]).addClass('active');
}
}
});

Categories

Resources