簡體   English   中英

根據下拉選擇問題禁用輸入字段

[英]Disable input field based on a drop down selection trouble

<div class="form-group form-animate-text col-lg-6 col-xs-12 col-md-6" >
    <select class="form-text" id="val_equipfc"  name="val_equipfc"  onChange="checkOption(this)" required>
        <option value = "A">Yes</option>
        <option value = "B">No</option>
    </select>
    <span class="bar"></span> 
    <label><span style="color:red">*</span>With Equipment?</span></label>
</div>

這是我的選擇類,這是輸入字段div

<div class="form-group form-animate-text col-lg-6 col-xs-12 col-md-6" >
    <input type="text" class="form-text" id="val_equipnofc" name="val_equipnofc">
    <span class="bar"></span> 
    <label><span style="color:red">*</span>Number of Equipment/s</label>
</div>

我在下拉菜單中單擊“否”時禁用輸入文本字段的jQuery如下:

function checkOption(obj) {
    var input = document.getElementById("val_equipnofc");
    input.disabled = obj.value == "B";
}

我想知道出什么問題了,當我搜索如何做時,我的代碼與網上的代碼相似,請告訴我出了什么問題。

首先,您似乎有一個標記問題(請參閱問題注釋)

然后,我將使用JavaScript添加事件監聽器,以避免出現無法加載JS的問題

document.getElementById ("val_equipfc").addEventListener ("change", ...)

並使用this關鍵字訪問新值。

看到這個小提琴


PS:如果只有“是/否”選項,為什么不使用復選框而不是下拉菜單

這是完整的HTML標記。

請測試一下。 這必須工作。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>This should work</title>
</head>
<body>
    <div class="form-group form-animate-text col-lg-6 col-xs-12 col-md-6">
        <select class="form-text" id="val_equipfc" name="val_equipfc" onChange="checkOption(this)" required>
            <option value="A">Yes</option>
            <option value="B">No</option>
        </select>
        <span class="bar"></span>
        <label><span style="color:red">*</span>With Equipment?</label>
    </div>

    <div class="form-group form-animate-text col-lg-6 col-xs-12 col-md-6">
        <input type="text" class="form-text" id="val_equipnofc" name="val_equipnofc">
        <span class="bar"></span>
        <label><span style="color: red">*</span>Number of Equipment/s</label>
    </div>

    <script type="text/javascript">
        function checkOption(obj) {
            var input = document.getElementById("val_equipnofc");
            input.disabled = obj.value == "B";
        }
    </script>
</body>
</html>

產生:

是的狀態:

在此處輸入圖片說明

無狀態:

在此處輸入圖片說明

如果您使用的是Jquery則可以這樣做

$(document).ready(function(){
  $('#val_equipfc').change(function(){
    $('#val_equipnofc').prop('disabled', $(this).val() == "B");
  });
});

在這里工作的JSFiddle https://jsfiddle.net/k4k24tq2/1/

暫無
暫無

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

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