简体   繁体   English

选择框 onchange 事件只有一个<option>

[英]Select box onchange event with only one <option>

The onchange event works great and populates my input (textbox) just fine, but when the onchange event is applied to the drop down box with only 1 single option in it, it does not work. onchange 事件效果很好,可以很好地填充我的输入(文本框),但是当 onchange 事件应用于只有 1 个选项的下拉框时,它不起作用。 How can I get the onchange to fire even if, there is one or multiple items?即使有一个或多个项目,我如何才能触发 onchange?

<!DOCTYPE html>

<html>

<head>

<style type="text/css">

</style>

<script type="text/javascript">
function test(x) {

    var x = document.getElementById(x).options[document.getElementById(x).selectedIndex].text

    document.getElementById('output').value = x

}//end of function
</script>

</head>

<body>
<select id="drop1" onchange="test(this.id)">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
<br><br>
<select id="drop2" onchange="test(this.id)">
  <option value="volvo">Volvo</option>
</select> 
<br><br>
<input type="text" id="output">

</body>

</html>

You could add an empty option at the top of every select box, or perhaps an option that just says -Select-.您可以在每个选择框的顶部添加一个空选项,或者添加一个仅显示 -Select- 的选项。 Then, if necessary, alter your script to ignore the empty selection.然后,如有必要,更改您的脚本以忽略空选择。

If there is only one item, it never will change.如果只有一项,它永远不会改变。 Try onblur instead.尝试使用onblur代替。 Or maybe onclick , depending on what you are actually trying to do.或者也许onclick ,这取决于您实际尝试做什么。

I am answering this question in case it can help somebody in 2020. I had the same problem populating data from the database into the form where there was a single data and I was able to solve this way.我正在回答这个问题,以防它可以在 2020 年帮助某人。我在将数据从数据库填充到只有单个数据的表单中时遇到了同样的问题,我能够以这种方式解决。 In the example am gonna use jquery for illustrations.在示例中,我将使用jquery进行插图。

First you have to empty the select element using .empty() function.首先,您必须使用.empty()函数清空 select 元素。

$('#drop2').empty();

Secondly add an empty value into the select using .append()其次使用.append()在选择中添加一个空值

$('#drop2').append("<option value='0'>Select</option>");

After that now you can go ahead to add your data into the select element because they are going to be two options, one empty while the other carries the data.之后,现在您可以继续将数据添加到 select 元素中,因为它们将是两个选项,一个为空,另一个携带数据。

Finally populate your data from server this way using ajax in success function最后使用成功函数中的ajax以这种方式从服务器填充数据

success:function(response){
                        $('#drop2').empty().append("<option value='0'>Select</option>");
                        response.forEach((item)=>{
                            $('#drop2').append("<option value='"+item[]+"'>"+item[1]</option>");

                        });

I have used the arrow function .forEach()我使用了箭头函数.forEach()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM