如果用户在另一个选择输入下拉列表中选择一个值,我试图禁用文本输入框。基本上,他们可以从列表中选择,也可以输入值,而不是两者。
我目前正在尝试这个片段,它似乎没有任何效果:
//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。
任何人都能看到我失踪的东西?
答案 0 :(得分:0)
首先,您可以选择不带冒号的输入,例如$('input')
。更重要的是,您希望使用selected
而不是disabled
设置.prop()
或.attr()
之类的内容。这是您的代码,包含这些更改。
//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);
});
答案 1 :(得分: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');
});