1

I have been playing around with the script 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>
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
John Higgins
  • 857
  • 12
  • 25

1 Answers1

1

The = assignment operator is used to assign values to a variable to the left of the sign. The == abstract equality operator or === strict equality operator is used to compare values.

function myFunction() {
  if(document.getElementById('select').value === 'option1') {
    option = 'option 1 choosen';
  }
  if(document.getElementById('select').value === 'option2') {
    option = 'option 2 choosen';
  }
  if(document.getElementById('select').value === 'option3') {
    option = 'option 3 choosen';
  }
  document.getElementById("demo").innerHTML = option;
}
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
  • I think you mean `==`, not `===`. – Wes Foster Sep 21 '16 at 15:55
  • 3
    no, "==" is truthy, in all professional code I have done "===" is the preferred method. http://stackoverflow.com/questions/5323377/difference-between-and-in-js –  Sep 21 '16 at 15:57
  • 1
    No. `==` is standard for comparing values. `===` is standard for comparing the value AND the type. In this instance, he's comparing values. **For example** Given that `x = 5`, `x == "5"` is true. `x === "5"` is false. – Wes Foster Sep 21 '16 at 15:59
  • 1
    all well and good. In the company I work for, "==" would fail code review. It might be technically correct....but it practice...it isn't. –  Sep 21 '16 at 16:00
  • 1
    @E.Maggini don't be bullied into accepting edits that conflict with your intent. You're absolutely right. – Patrick Roberts Jan 20 '19 at 07:11