wyc
wyc

Reputation: 55263

Using jQuery to test if the user has typed in an input?

I have a variable called $places:

    var $places = $('#resultsListing li.place');

When there are more than 0 places the following code add the class .have-results. If there are 0 results the code adds the class .no-results to the body:

body.removeClass("have-results no-results searching");

body.addClass(places.length > 0 ? "have-results" : "no-results");
$("div#busyAnimation").hide();

I would like to add another class called .hasnt-typed-yet. I know it is a horrible name for a class, but that's what I want to accomplish; add that class to the body if the user hasn't typed yet in the input.

Any suggestions to accomplish this?

Upvotes: 1

Views: 316

Answers (3)

Samuel Liew
Samuel Liew

Reputation: 79022

$textbox = $('#searchbox');
$body = $('body').filter(':first');
$places = $('#resultsListing li.place');

$textbox.keyup(function() {
    if($(this).val() == '') $body.addClass('hasnt-typed-yet');
    else $body.removeClass('hasnt-typed-yet');
});

$body.addClass($places.length > 0 ? 'have-results' : 'no-results');
$('#busyAnimation').hide();

Upvotes: 0

Yacov
Yacov

Reputation: 1070

if($('input').val() == '')
    $('body:first').addClass('hasnt-typed-yet')
else
    $('body:first').removeClass('hasnt-typed-yet')

Upvotes: 0

Milan Jaric
Milan Jaric

Reputation: 5646

var textbox_text = $("#searchbox").val(); 
if(textbox_text !== '' ){
    body.addClass(places.length > 0 ? "have-results" : "no-results");
}else{
   body.addClass('hasnt-typed-yet');
}
$("div#busyAnimation").hide();

Upvotes: 2

Related Questions