Jfabs
Jfabs

Reputation: 563

Check if textbox has value then disable form element

If my textbox has text in it, I want to disable the drop down list. The textbox id is "newAccessPoint" and the drop down list id is "selectAccessPoint"

jQuery:

if ($.trim($('#newAccessPoint').val()).length() != 0) {
    $('#selectAccessPoint').attr('disabled', 'disabled');
}

HTML markup:

<table class="data-table">
    <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>

Upvotes: 3

Views: 5373

Answers (3)

James Donnelly
James Donnelly

Reputation: 128791

The problem is that you have length(). length is a property, not an object. You need to use just length.

if ($.trim($('#newAccessPoint').val()).length != 0) {
    $('#selectAccessPoint').attr('disabled', 'disabled');
}

Depending on which version of jQuery you're using, you'll want to use prop() instead of attr():

if ($.trim($('#newAccessPoint').val()).length != 0) {
    $('#selectAccessPoint').prop('disabled', true);
}

Edit (from comments):

Here is a JSFiddle demo of this in use on textbox input, which disables the select element when the textbox has content, then re-enables it when it is cleared.

Upvotes: 3

konnigun
konnigun

Reputation: 1805

What you need is onBlur event handler:

<input type="text" id="newAccessPoint">
<select id="selectAccessPoint">
    <option>test</option>
</select>
$('#newAccessPoint').blur(function() {
    if($('#newAccessPoint').val().length > 0) {
            $('#selectAccessPoint').attr('disabled', 'disabled');
    }
});

http://jsfiddle.net/Z4TRt/

Upvotes: 1

palaѕн
palaѕн

Reputation: 73896

Try this using the .length method properly and prop() method:

if ($.trim($('#newAccessPoint').val()).length != 0) {
    $('#selectAccessPoint').prop('disabled', true);
}

Upvotes: 1

Related Questions