John John - 4 months ago 14
HTML Question

Selected option does not run script

I am using the HTML

<select>
for selecting options. The first value in my select is
selected
. For all of these options I have a javascript that runs different scripts.

When I change the value to 2 the javascript runs the script for value 2
(dataEl.value === "2") { outputEl.innerHTML = '<div>result option two</div>';


The script works only when the value is changed and does not show the script for value 1 when the selected option is not changed.

Does someone know how I can solve this?

Here is my script:

JSFiddle

https://jsfiddle.net/yua9vanz/

HTML

<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Select</label>
<div class="col-md-9 col-sm-9 col-xs-12">
<select class="form-control select2" id="select" name="select" style="width: 100%;">
<option selected="selected" value="1">Option one</option>
<option value="2">Option two</option>
<option value="3">Option three</option>
</select>
</div>
</div>

<p id="output1"></p>

<script type="text/javascript">
var dataEl = document.querySelector('#select'),
outputEl = document.querySelector('#output1');

dataEl.onchange = function() {
if (dataEl.value === "1") {
outputEl.innerHTML = '<div>result option one</div>';

} else if (dataEl.value === "2") {
outputEl.innerHTML = '<div>result option two</div>';

} else if (dataEl.value === "3") {
outputEl.innerHTML = '<div>result option three</div>';
}
};
</script>

Answer Source

I think this is what you want, I modified the code a bit, but in summary, I just added the onload event in the element(#select).

var dataEl = document.querySelector('#select'),
  outputEl = document.querySelector('#output1');

dataEl.addEventListener("load", check());

function check() {
  if (dataEl.value === "1") {
    outputEl.innerHTML = '<div>result option one</div>';

  } else if (dataEl.value === "2") {
    outputEl.innerHTML = '<div>result option two</div>';

  } else if (dataEl.value === "3") {
    outputEl.innerHTML = '<div>result option three</div>';
  }
}
<div class="form-group">
  <label class="control-label col-md-3 col-sm-3 col-xs-12">Select</label>
  <div class="col-md-9 col-sm-9 col-xs-12">
    <select class="form-control select2" id="select" name="select" style="width: 100%;" onchange="check()">
      <option selected="selected" value="1">Option one</option>
      <option value="2">Option two</option>
      <option value="3">Option three</option>
    </select>
  </div>
</div>

<p id="output1"></p>