I have a dropdown that runs a script when the value is changed. But now I want to return the selected value from the database and run a script when the selected value is: 2
.
Here is my dropdown:
<div class="col-md-9 col-sm-9 col-xs-12">
<select class="form-control select2" id="status" name="status" style="width: 100%;">
<option <?php echo ($row["status"] == "1") ? 'selected="selected"' : '';?> value="1">One</option>
<option <?php echo ($row["status"] == "2") ? 'selected="selected"' : '';?> value="2">Two</option>
</select>
</div>
The result of the output should deployed here:
<p id="output1"></p>
This is the script that is running onchange:
<script type="text/javascript">
var dataEl = document.querySelector('#status'),
outputEl = document.querySelector('#output1');
dataEl.onchange = function() {
if (dataEl.value === "1") {
outputEl.innerHTML = ' ';
} else if (dataEl.value === "2") {
outputEl.innerHTML = '<div>(script)</div>';
}
};
</script>
I want to keep the script for onchange. But I also want to run this script when the returned value from the database = 2
. I tried different scripts like adding a dataEl.onLoad
script, but also this didnt show the script for value 2
.
Does someone know how I can do this?
To get the selected value of select options you need to use selectedIndex
.
var e = document.getElementById("status");
var sel = e.options[e.selectedIndex].value;
Primary Example: https://jsfiddle.net/z1wyz62s/
Complete example by @John: https://jsfiddle.net/z1wyz62s/3/
Why don't you just call it?
dataEl.onchange = function() {
if (dataEl.value === "1") {
outputEl.innerHTML = ' ';
} else if (dataEl.value === "2") {
var result = your_script();
outputEl.innerHTML = '<div>'+result+'</div>';
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.