[英]Run script when database return a value
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
. 但是现在我想从数据库中返回选定的值,并在选定的值为:
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: 这是在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. 我想保留脚本进行onchange。 But I also want to run this script when the returned value from the database =
2
. 但是,当数据库返回的值=
2
时,我也想运行此脚本。 I tried different scripts like adding a dataEl.onLoad
script, but also this didnt show the script for value 2
. 我尝试了其他脚本,例如添加
dataEl.onLoad
脚本,但这也没有显示值2
的脚本。
Does someone know how I can do this? 有人知道我该怎么做吗?
To get the selected value of select options you need to use selectedIndex
. 要获得选择选项的选定值,您需要使用
selectedIndex
。
var e = document.getElementById("status");
var sel = e.options[e.selectedIndex].value;
Primary Example: https://jsfiddle.net/z1wyz62s/ 主要示例: https : //jsfiddle.net/z1wyz62s/
Complete example by @John: https://jsfiddle.net/z1wyz62s/3/ @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>';
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.