bourki bourki -3 years ago 181
Javascript Question

low level JAVASCRIPT, cant return a picture value with variable X

So basically I am making a menu and every time the user clicks on a select option, the image of his meal choice appears. I want to also make my function return the price of the item when the option is selected. My pictures work on select, but my "demo" will not change to the value of the item and I need help from you guys.

<select name="entree" id="entree" onChange="changeit(this.value)">
<option value="hidden" selected>Choisir...</option>
<option value="salade">Salade</option>
<option value="escargot">Escargot</option>
</select><br />
<img id="imgselect" src="" alt="demo"/>
<h3 id= "demo1"></h3>

<select name="entree" id="entree" onChange="changerepas(this.value)">
<option value="hidden1" selected>Choisir...</option>
<option value="spaghetti">Spaghetti</option>
<option value="lasagne">Lasagne</option>
</select>
<br />
<img id="imgselect1" src="" alt="demo"/>
<h3 id="demo"></h3>





function changeit(option) {
var image;
var price;

switch (option) {
case "salade":
image = "salade.jpg";
price = "5.95$";
break;
case "escargot":
image = "escargot.jpg";
price = "4.95$";
break;
case "hidden":
image = "vile.jpg";
price = "";
break;
default:
break;
}

document.getElementById("imgselect").setAttribute("src", image);
document.getElementById("demo1").innerHTML = price;
}
function changerepas(option) {
var image;
var price;

switch (option) {
case "spaghetti":
image = "spaghetti.jpg";
price = "8.95$";
break;
case "lasagne":
image = "lasagne.jpg";
price = "9.95$";
break;
case "hidden1":
image = "vide.jpg";
price = "";
break;
default:
break;
}

document.getElementById("imgselect1").setAttribute("src", image);
document.getElementById("demo").innerHTML = price;
}

Answer Source

Use innerHTML to change the content of a HTML element.

Moreover, you should use a switch to change options, it's much more efficient than rewriting the same code over and over again.

function changeit(option) {
    var image;
    var price;

    switch (option) {
    case "salade":
        image = "salade.jpg";
        price = "5.95$";
        break;
    case "escargot":
        image = "escargot.jpg";
        price = "4.95$";
        break;
    case "hidden":
        image = "vile.jpg";
        price = "";
        break;
    default:
        break;
    }

    document.getElementById("imgselect").setAttribute("src", image);
    document.getElementById("demo1").innerHTML = price;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download