Reputation: 169
I can't seem to find the documentation that discusses this, so I thought maybe someone on here could help. I want to write a javascript if/else function that triggers multiple events. My code is a little rough, but I think it should look like:
function getFruit() {
var x = document.getElementById("myinput").value;
var score;
var picture;
if (x === "Apple") {
score = "A" || pciture = "http://exampple.com/assets/apple.jpg";
else(x === "Banana") {
score = "B" || picture = "http://example.com/assets/banana.jpg";
}
document.getElementById("text").innerHTML = score;
document.getElementById("display").image.src = picture;
}
<input type="text" id="myinput">
<p id="text"></p>
<img id="display"></img>
Upvotes: 0
Views: 1276
Reputation: 1885
If you want to have a cleaner code, and avoid to have the same variable assignment all over the place you should wrap everything in an Object and use the input's value to access the properties
// Call this function differently renderFruit, or loadFruit, etc
function getFruit() {
var x = document.getElementById("myinput").value;
var fruits = {
Apple: {
score: 'A',
picture: 'https://via.placeholder.com/300x120?text=Apple'
},
Banana: {
score: 'B',
picture: 'https://via.placeholder.com/300x120?text=Banana'
}
};
var f = fruits[x];
document.getElementById("text").innerHTML = f && f.score;
document.getElementById("display").src = f && f.picture;
// Please don't name getSomething to a function that does not
// have a return statement e.g.: return f;
}
<input type="text" id="myinput" onchange="getFruit()">
<p id="text"></p>
<img id="display" />
Upvotes: 0
Reputation: 5648
Multiple errors of syntaxis in your code.
This is a correct if/else statement
if (x === "Apple") {
...
} else {
...
}
function getFruit() {
var x = document.getElementById("myinput").value;
var score;
var picture;
if (x === "Apple") {
score = "A";
picture = "http://exampple.com/assets/apple.jpg";
} else {
score = "B";
picture = "http://example.com/assets/banana.jpg";
}
document.getElementById("text").innerHTML = score;
document.getElementById("display").src = picture;
}
<input type="text" id="myinput">
<p id="text"></p>
<img id="display" src="">
<button onclick="getFruit()">Check</button>
Upvotes: 0
Reputation: 3120
You just need them on different lines. There is no reason for doing the ||
.
function getFruit() {
var x = document.getElementById("myinput").value;
var score;
var picture;
if (x === "Apple") {
score = "A";
picture = "http://exampple.com/assets/apple.jpg";
}
else if (x === "Banana") {
score = "B";
picture = "http://example.com/assets/banana.jpg";
}
document.getElementById("text").innerHTML = score;
document.getElementById("display").image.src = picture;
}
Upvotes: 1