2016-08-15 67 views
0

我试图禁用文本输入框,如果用户在另一个选择输入下拉列表中选择一个值。基本上,他们可以从列表中选择,或者输入一个值,而不是两个值。当用户选择选项时禁用文本输入

我目前想这个片段中,这似乎并没有遇到的任何影响:

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

编辑:为更好的语法

请注意,我必须使用查找(”更新代码:input'),因为我与嵌套在由插件生成的代码中的字段进行交互,所以我不能给这些字段本身提供正确的ID。

有人看到我失踪了吗?

+0

我认为这个问题是我没有从选择2输入正确获取值,但我无法找出正确的方式.... – Eckstein

回答

0

首先,您可以选择不带冒号的输入,如$('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); 
}); 
+0

酷的感谢!它仍然不起作用。由于其中一个输入是选择下拉菜单,它是否应该只是'输入'或我需要使用'选择'? – Eckstein

+0

是的,这是正确的。将其改为'.find('select')'。 –

+0

谢谢。即使有这些变化,不幸的是没有运气。 – Eckstein

0

想通了。这里是工作的解决方案:

//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'); 
});