2016-08-15 89 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'); 
});