StudioTime
StudioTime

Reputation: 23979

jquery check for form field length

I have the following form and I want to ensure the user enters at least two characters before the form can be submitted. So I disable the submit button:

<form action="/search" method="post" id="search_form" name="searchform">
<input id="search_box" type="text" class="inp" placeholder="Search" />
<input type="submit" id="search_button" disabled class="btn" value="Search">
</form>

Am trying the following Jquery to capture the keypresses but not happening:

$("#search_box").keypress(function() {
if($(this).length > 1) {
     $('#search_button').removeAttr('disabled');
}
});

I've set up a fiddle to show: http://jsfiddle.net/HZvSF/3/

Upvotes: 0

Views: 792

Answers (2)

jenson-button-event
jenson-button-event

Reputation: 18941

You need to get the val() of your textbox:

$("#search_box").keypress(function() {
if($(this).val().length > 1) {
     $('#search_button').removeAttr('disabled');
}
});

edit

I just saw the library was MooTools in fiddle, here it is working: http://jsfiddle.net/HZvSF/17/

Upvotes: 2

artragis
artragis

Reputation: 3713

I think it is a problem of binding. inside the anonymous function "this" does not refer to je JQuery object but to window I think.

$("#search_box").keypress(function(event) {
if($(event.target).val().length > 1) {
     $('#search_button').removeAttr('disabled');
}
});

Upvotes: 0

Related Questions