codemaniac
codemaniac

Reputation: 67

How can I change the output value of an <option> if selected?

How can I give one element of a dropdown list a value and another element a different value?

I'm trying to output the different values into a input field when selected.
The following is just a visual, so you can understand the problem.

<label>Dropdown-List</label>
<select class="form-control" onchange="handicap();">
<option id="c1">Example (5)</option>
<option id="c2">Example (10)</option>

<input type="text" class="form-control" id="cap">

function handicap() {

  var cap1 = document.getElementById('c1');
  var cap2 = document.getElementById('c2');

  if (cap1) {
     document.getElementById('cap').value = 5;
  }

  else {
     document.getElementById('cap').value = 10;
  }
}

Upvotes: 1

Views: 309

Answers (1)

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

Your condition should be cap1.selected instead of cap1. The condition you have at the moment becomes true in if(cap1) if cap1 is not null or undefined thus, in each case cap1 is defined so you were always getting that condition satisfied and the input was set with the value of 5 but now when you do cap1.selected it actually checks if the option cap1 is selected or not.

function handicap() {
  var cap1 = document.getElementById('c1');
  var cap2 = document.getElementById('c2');
  if (cap1.selected) {
     document.getElementById('cap').value = 5;
  }
  else {
     document.getElementById('cap').value = 10;
  }
}
<label>Dropdown-List</label>
<select class="form-control" onchange="handicap();">
<option id="c1">Example (5)</option>
<option id="c2">Example (10)</option>

<input type="text" class="form-control" id="cap">

Upvotes: 1

Related Questions