javascript jQuery 下拉选择事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17966286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery dropdown select event
提问by theMojoWill
Is there a specific event for when a user selects an item in a dropdown box? I am creating a fairly large form that uses multiple dropdown boxes. On load all but the first are disabled, as the user selects the first option the options in the second box change using AJAX and I want to remove the attribute disabled.
用户在下拉框中选择项目时是否有特定事件?我正在创建一个相当大的表单,它使用多个下拉框。在加载时,除第一个之外的所有选项都被禁用,因为用户选择第一个选项,第二个框中的选项使用 AJAX 更改,我想删除禁用的属性。
$('#site_id').on('change', function(event) {
$('#access_type_id').removeAttr('disabled');
});
The trouble I am having is that .change()
seems to be fired when the options in a dropdown change making following dropdown boxes enabled before I actually want them to be. Is there an alternative event I can use in place of change to only "enable" a form field once the user has made their selection in the previous dropdown?
我遇到的问题是,.change()
当下拉列表中的选项更改使以下下拉框在我真正想要它们之前启用时,似乎会被触发。一旦用户在上一个下拉列表中进行了选择,我是否可以使用替代事件来代替更改以仅“启用”表单字段?
UPDATE
更新
I managed to solve this by not using the change event at all and placing my removeAttr in the success section of my AJAX call. An example is below. This allowed me to make the "next" dropdown enabled at the time as populating its options.
我设法通过根本不使用更改事件并将我的 removeAttr 放在我的 AJAX 调用的成功部分来解决这个问题。下面是一个例子。这使我可以在填充其选项时启用“下一个”下拉列表。
$('#access_speed_id').on('select2-blur', function(event){
$.ajax({
async: true,
data: $('#access_speed_id').serialize(),
dataType: 'html',
success: function(data, textStatus) {
$('#cdr_id').removeAttr('disabled');
$('#cdr_id').html(data);
},
type: 'post',
url: '/services/specificCdrs'
});
});
回答by Nitin Chaurasia
Try Below code:
试试下面的代码:
<select id="drop1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="drop2"></select>
Jquery
查询
$(document).ready(function(){
$("#drop2").attr("disabled", true);
$("#drop1").change(function(){
$("#drop2").attr("disabled", false);
//Put your ajax code here and bind like below code
$("#drop2").append(new Option("option text", "value"));
$("#drop2").append(new Option("xxx","1"));
});
});