John Higgins
John Higgins

Reputation: 907

Display input value depending on select

I am trying to display a result in an input box depending on a select.

So, if "1" is select the input will show "one" and if "2" is selected the input will show "two".

My code below will not allow to select "2" as an option.

function SelectData(data) {

  if (data.value = "1") {
    document.getElementById("result").value = "one";
  } else if (data.value = "2") {
    document.getElementById("result").value = "two";
  }

}
<select onchange="SelectData(this)">
  <option value='1'>1</option>
  <option value='2'>2</option>
</select>

<input id="result" disabled>

Can anyone help?

Many thanks,

John

Upvotes: 0

Views: 64

Answers (2)

Sarah Gro&#223;
Sarah Gro&#223;

Reputation: 10879

You are using the wrong operator in your if/else if statements. = will set a variable to a value, == will check if a variable equals a value.

There is also another operator, === which acts type-specific:

  • "1" == true will evaluate to true
  • "1" === true will evaluate to false

whereas

  • 1 === 1 or true === true will evaluate to true again.

function SelectData(data) {

if (data.value == "1") {
document.getElementById ("result").value = "one";
}

else if (data.value == "2") {
document.getElementById ("result").value = "two";
}

}
<select onchange="SelectData(this)">
<option value='1'>1</option>
<option value='2'>2</option>
</select>

<input id="result" disabled>

Upvotes: 1

You have to use == not =

data.value == "1" ask if the value is equal 1

data.value = "1" set the value to 1

function SelectData(data) {

  if (data.value == "1") {
    document.getElementById("result").value = "one";
  } else if (data.value == "2") {
    document.getElementById("result").value = "two";
  }

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select onchange="SelectData(this)">
  <option value='1'>1</option>
  <option value='2'>2</option>
</select>

<input id="result" disabled>

Upvotes: 1

Related Questions