jQuery下拉选择事件 [英] jQuery dropdown select event

查看:160
本文介绍了jQuery下拉选择事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户在下拉框中选择项目时是否存在特定事件?我正在创建一个使用多个下拉框的相当大的表单.在加载时,除第一个选项外的所有选项均被禁用,因为用户选择了第一个选项,第二个框中的选项将使用AJAX更改,而我想删除禁用的属性.

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.

$('#site_id').on('change', function(event) {
    $('#access_type_id').removeAttr('disabled');
});

我遇到的麻烦是,当下拉列表中的选项更改之后,在我实际希望它们启用之前,启用了以下下拉框时,似乎会触发.change().用户在上一个下拉列表中进行选择后,是否可以使用其他事件代替更改以仅启用"表单字段?

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事件来解决此问题,并将removeAttr放在我的AJAX调用的成功部分中.下面是一个示例.这使我能够在填充其选项时同时启用下一个"下拉菜单.

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.

$('#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'
    });
});

推荐答案

尝试以下代码:

<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"));        
});
});

演示: http://jsfiddle.net/J5kmz/

这篇关于jQuery下拉选择事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆