【问题标题】:Disable text input when user selects option用户选择选项时禁用文本输入
【发布时间】:2016-12-21 05:30:39
【问题描述】:

如果用户在另一个选择输入下拉列表中选择了一个值,我正在尝试禁用文本输入框。基本上,他们可以从列表中选择,也可以输入一个值,不能同时输入。

我目前正在尝试这个sn-p,它似乎没有任何效果:

//If the #chooseOrg select box has a value, we disable the #enterOrg box
var chosen = $('#chooseOrg').find('select');
var enterInput = $('#enterOrg').find('input');
if (chosen.val()) {
     enterInput.prop('disabled', true);
}

//On the new listings pages, for producer/org select
//Disable the text box input if the user selects an org from the list
$('#chooseOrg').find('select').on('select2-selecting', function() {
     if ($(this).val()) {
          enterInput.prop('disabled', true);
     }   
});
//Re-enable the text input if they clear their selection
$('#chooseOrg').find('select').on('select2-removed', function() {
     $('#enterOrg').find('input').prop('disabled', false);
});

编辑:更新代码以获得更好的语法

请注意,我必须使用 find(':input'),因为我正在与嵌套在插件生成的代码中的字段进行交互,因此我无法为字段本身提供正确的 ID。

有人看到我错过了什么吗?

【问题讨论】:

  • 我认为问题是我没有从 select2 输入中正确获取值,但我想不出正确的方法......

标签: jquery validation input


【解决方案1】:

首先您可以选择不带冒号的输入,例如$('input')。更重要的是,您需要使用.prop() 而不是.attr() 来设置selecteddisabled 之类的东西。这是您进行这些更改的代码。

//If the #chooseOrg select box has a value, we disable the #enterOrg box
var chosen = $('#chooseOrg').find('input');
var enterInput = $('#enterOrg').find('input');
if (chosen.val()) {
    enterInput.prop('disabled', true);
}

//On the new listings pages, for producer/org select
//Disable the text box input if the user selects an org from the list
$('#chooseOrg').find('input').on('select2-selecting', function() {
    if ($(this).val()) {
        enterInput.prop('disabled', true);
    }   
});
//Re-enable the text input if they clear their selection
$('#chooseOrg').find('input').on('select2-removed', function() {
    $('#enterOrg').find('input').prop('disabled', false);
});

【讨论】:

  • 很酷,谢谢!它仍然无法正常工作。由于其中一个输入是一个选择下拉菜单,它是否仍然应该只使用“输入”或者我需要使用“选择”?
  • 是的,没错。将其更改为 .find('select')
  • 谢谢。即使有这些变化,不幸的是没有运气。
【解决方案2】:

想通了。这是可行的解决方案:

//Disable the text input box of the selection already has a value
$('#chooseOrg').ready(function() {
    var chosen = $(this).find('select').val();
    var enterInput = $('#enterOrg').find('input');
    if (chosen) {
        enterInput.attr('disabled', true);
    }   
});
//Disable the text box input if the user selects an org from the list
$('#chooseOrg').on('select2-selecting', function() {
    var chosen = $(this).val();
    var enterInput = $('#enterOrg').find('input');
    if (chosen !== null) {
        enterInput.attr('disabled', true);
    }   
});
//Re-enable the text box input if they clear their selection
$('#chooseOrg').on('select2-removed', function() {
    $('#enterOrg').find('input').removeAttr('disabled');
});

【讨论】:

    猜你喜欢
    • 2018-07-21
    • 2022-09-23
    • 2013-06-29
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    相关资源
    最近更新 更多