根据下拉列表启用/禁用表单元素

时间:2013-05-15 15:32:57

标签: jquery

所以我一直在寻找这里的问题,我已经足够远,可以通过更改textbox的选择来禁用dropdownlist,但我希望能够启用如果dropdownlist返回其默认值<Select an Access Point>,则会再次显示。

JQuery:

$('#selectAccessPoint').change(function () {
    if ($('#selectAccessPoint :selected').val != "2147483647")
        $('#newAccessPoint').attr('disabled', 'disabled');
    else {
        $('#newAccessPoint').removeAttr('disabled');
        $('#newAccessPoint').attr('enabled', 'enabled');
    }
});

textboxdropdownlist的HTML: `

        <tr>
        <td><label for ="AccessPoint" class="xl">Access Point:</label></td>
            <td><%= Html.DropDownListFor(x => x.AccessPointsList.Id, Model.AccessPointsList.AccessPoints.OrderByDescending(x => x.Value.AsDecimal()), new { @id = "selectAccessPoint", @class = "info1"})%></td>
        </tr>
        <tr>
            <td><label for ="AccessPoint" class="xl">Or Add New:</label></td>
            <td><%= Html.TextBoxFor(x => x.AccessPointsList.AccessPoint, new { @id = "newAccessPoint", @class = "location info2 xl", maxlength = "250" }) %></td>
        </tr>

生成的HTML: <select class="info1" data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="selectAccessPoint" name="AccessPointsList.Id"><option value="2147483647">&lt;Select an Access Point&gt;</option> (那里有更多选项,但这是我正在比较的那个)

<input class="location info2 xl" id="newAccessPoint" maxlength="250" name="AccessPointsList.AccessPoint" type="text" value="">

注意:必须使用attr prop给我一个错误,而val()也会给我一个错误。

2 个答案:

答案 0 :(得分:6)

使用jquery v1.9.1

$('#selectAccessPoint').change(function () {
    if ($(this).find('option:selected').text() != '<Select an Access Point>') {
        $('#newAccessPoint').prop('disabled', true);
    } else {
        $('#newAccessPoint').prop('disabled', false)
    }
});
  • $('#selectAccessPoint:selected')不正确。它应该是$('#selectAccessPoint option:selected')
  • .text不正确。它应该是.text()
  • 禁用文本框,只需使用jquery v1.9.1使用此prop('disabled', true)
  • 启用文本框,只需使用此prop('disabled', false)

使用jquery v1.4.4

$('#selectAccessPoint').change(function () {
    if ($(this).find('option:selected').text() != 'Select an Access Point') {
        $('#newAccessPoint').attr('disabled', 'disabled');
    } else {
        $('#newAccessPoint').attr('disabled', '')
    }
});

答案 1 :(得分:0)

你可能想尝试这样的事情

HTML

<select name="foo" id="foo" onChange="javascript:changeTextBoxState(this)">
  <option>Select Something</option>
  <option>FooBar</option>
</select>

<input name="bar" id="bar" type="text" />

的jQuery

function changeTextBoxState(dropDown) {

  switch (dropDown.value) {
    case 'Select Something': {
       $('#bar').removeAttr("disabled");
    }
    case 'FooBar': {
       $('#bar').addAttr('disabled', 'disabled');
    }
  }
}

仅禁用输入标记上的启用属性。

希望这有帮助

相关问题