John Higgins John Higgins - 2 months ago 5
Javascript Question

If then else using javascript

I have been playing around with the script (a javascript newbie!) and can't get it working. It always defaults to option3.

Can anyone help?

<select id="select">
<option>Please select</option>
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
</select>
<div id="demo"></div>

<script>

document.getElementById("select").addEventListener("change", myFunction);

function myFunction() {
if (document.getElementById("select").value = "option1") {
option = "option 1 chosen";
}
if (document.getElementById("select").value = "option2") {
option = "option 2 chosen";
}
if (document.getElementById("select").value = "option3") {
option = "option 3 chosen";
}
document.getElementById("demo").innerHTML = option;
}

</script>


Thanks,

John

Answer

You should use === instead of =

as stated in comments, "=" is an assign function, "===" is a comparison function.

function myFunction() {
if (document.getElementById("select").value === "option1") {
option = "option 1 chosen";
}
if (document.getElementById("select").value === "option2") {
option = "option 2 chosen";
}
if (document.getElementById("select").value === "option3") {
option = "option 3 chosen";
}
document.getElementById("demo").innerHTML = option;
}
Comments