Zach Brantmeier
Zach Brantmeier

Reputation: 746

Checking textbox if it's empty in Javascript

I wrote a simple html file with a textbox and submit button, and it generates and document.write's a response dependant on what you submit. I want to have it generate a response saying to enter content if the box is empty. The textbox's id is chatinput, so I have the following the code in the beginning

    var chatinput_box=document.getElementById('chatinput');
    var chatinput=chatinput_box.value;

Then a have a conditional, although I can't get it to work correctly; I've tried

    if(chatinput==""){}
    if(chatinput.length=0){}
    if(chatinput=null){}

and others but none have worked correctly. Does anyone have another idea?

Upvotes: 10

Views: 40030

Answers (2)

user2742371
user2742371

Reputation:

It should be this:

var chatinput = document.getElementById("chatinput").value;
if (chatinput == "" || chatinput.length == 0 || chatinput == null)
{
    // Invalid... Box is empty
}

Or shorthanded:

if (!document.getElementById("chatinput").value)
{
    // Invalid... Box is empty
}

The = assigns a value whereas == checks whether the values are equal.

Upvotes: 19

PlantTheIdea
PlantTheIdea

Reputation: 16359

Just offering an alternative, not trying to steal thunder ...

Create an isEmpty function to reuse on a variety of items.

function isEmpty(val){
    return ((val !== '') && (val !== undefined) && (val.length > 0) && (val !== null));
}

Then you can apply it to whatever element you want:

if(!isEmpty(chatinput)){
    // hooray its got a value!
}

Not exactly original, its the concept stolen from PHP, but it comes in handy a lot.

Upvotes: 3

Related Questions