基于下拉列表启用/禁用表单元素



所以我一直在这里寻找问题,我已经走得足够远,能够通过改变dropdownlist的选择来禁用textbox,但我希望能够再次启用它,如果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()也给了我一个错误。

使用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', '')
    }
});

您可能想尝试这样做

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');
    }
  }
}

输入标签上没有启用的属性,只有禁用的。

希望能有所帮助

最新更新