簡體   English   中英

同時基於單選按鈕和選擇選項的啟用和禁用表單的字段

[英]Enabling & disabling form's field based on the choice of radio button & select option together

在此處輸入圖片說明

在上面的表格中,當用戶選擇“ No單選按鈕Want it? 字段的以下選擇菜單, If yes, how? 字段和Address字段的文本輸入區域應被禁用。

如果用戶選擇“ Yes ,則應同時啟用以下兩個字段,其中用戶應優先選擇“ If yes, how?的選擇菜單中的投放方式If yes, how? 字段是:

home_delivery

pos_delivery

如果用戶選擇pos_delivery ,則應禁用“ Address字段的文本輸入區域。

html和jQuery代碼如下:

<table>
<tr>
<td>Want it?</td>
<td><input type="radio" name="choose" id="yes" value="Yes" />Yes</td>
<td><input type="radio" name="choose" id="no" value="No" />No</td>
</tr>
<tr>
<td>If yes, how?</td>
<td>
<select name="delivery_method" id="delivery_method">
<option value="" selected="selected">Select Delivery Method</option>
<option value="home_delivery">Home Delivery</option>
<option value="pos_delivery">Point of Sale Delivery</option>
</select>
</td>
</tr>
<tr>
<td>Address:</td>
<td><input name="address" id="address" type="text" value="" size="30" />
</td>
</tr>

<script type="text/javascript">
jQuery(document).ready(function($){
$('input[name="choose"]').on('click', function() {
    if ($(this).val() === 'Yes') {
        $('#delivery_method,#address').removeProp("disabled");
    }else{
        $('#delivery_method,#address').prop("disabled", "disabled");
    }
});disabled
});
</script>
</script>-->
<script type="text/javascript">
jQuery(document).ready(function($){
$('#address').attr('disabled','disabled');        
$('select[name="delivery_method"]').on('change',function(){
var  option = $(this).val();
    if(option === "home_delivery"){           
    $('#address').removeAttr('disabled');          
     }else{
     $('#address').attr('disabled','disabled'); 
    }  
  });
});
</script>

以下jQuery代碼塊分別用於此目的,但是當將它們組合在一起時,以下兩個jQuery代碼塊似乎相互沖突。

在這種情況下,如何將這兩個代碼塊組合在一起?

只需更換...

$('#delivery_method,#address').removeProp("disabled", "disabled");

...有了這個...

$('#delivery_method,#address').prop("disabled", false);

另外,由於某種原因,您以某種方式留下了disabled函數或語句:

jQuery(document).ready(function($){
    $('input[name="choose"]').on('click', function() {
        if ($(this).val() === 'Yes') {
            $('#delivery_method,#address').prop("disabled", false);
        }else{
           $('#delivery_method,#address').prop("disabled", "disabled");
        }
    });disabled /* <-- this one */
});

...只要刪除它,您就應該做好了。

編輯:一點解釋: removeProp僅采用一個屬性,因此您可以正確使用它...

$('#delivery_method,#address').removeProp("disabled");

...或使用prop進行相同操作,如上所示。

這是一個小提琴演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM