在页面加载和更改时删除属性

Remove Attributes on Page Load and On Change

如何在页面加载和下拉选择发生变化时根据下拉列表的值删除属性和"gray out"文本框?我已尝试遵循建议 here and here,但它似乎只对下拉菜单更改有效。 Visual Studio 或 Chrome 控制台中未显示任何错误。

视图有一个下拉菜单,它加载了用户保存的选择,文本框只有在下拉选择更改并改回后才不可用,此时下拉值的原始值也应该最初加载文本框作为不可用。换句话说,文本框应该在下拉值 == 1 的每个点都不可用,但以下内容似乎没有这样做:

<div class="col-md-12" style="clear: left;">
    <label for="preferenceId" class="req">Preference</label>
    <div class="col-xs-8 no-left">
        @Html.DropDownListFor(m => m.PreferenceTypeID, StaticCache.GetPreferenceTypes(), new { @class = "form-control", data_parsley_required = "true" })
    </div>
    <div class="col-xs-4 no-right">
        <div id="customAmount">
            @Html.TextBoxFor(m => m.PreferenceCustomAmount, new { @class = "form-control" })
        </div>
    </div>
</div>

@section Scripts{
   <script>
    $(function () {
        if ($("#PreferenceTypeID").val() != 1) {
            $("#PreferenceCustomAmount").hide();
        } else {
            $("#PreferenceCustomAmount").show();
        }
    });
    $("#PreferenceTypeID").change(function () {
        if ($("#PreferenceTypeID").val() == 1) {
            $("#PreferenceCustomAmount").attr("disabled", "disabled");
        } else {
            $("#PreferenceCustomAmount").removeAttr("disabled", "disabled");
        }
    });
    </script>
}

In other words, the text box should be unavailable at every point where the dropdown value == 1

你最好在加载时也触发 .change()。使用 .prop() 到 add/remove 元素属性。看看下面的代码。

$(function() {

    var $amountInput = $("#PreferenceCustomAmount");
    $("#PreferenceTypeID").change(function () {
        if ( this.value == 1 ) {
            $amountInput.prop("disabled", true);
        } else {
            $amountInput.prop("disabled", false);
        }
    }).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12" style="clear: left;">
    <label for="preferenceId" class="req">Preference</label>
    <div class="col-xs-8 no-left">
        <select id="PreferenceTypeID">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
        </select>
    </div>
    <div class="col-xs-4 no-right">
        <div id="customAmount">
            <input type="text" id="PreferenceCustomAmount" />
        </div>
    </div>
</div>