zchbrntmr zchbrntmr - 4 months ago 11
HTML Question

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?

Answer

It should be this:

var chatinput = document.getElementById("chatinput").value;

if (chatinput == "" || chatinput.length == 0 || chatinput == null)
{
    // Invalid... Box is empty
}

Or shorthanded (Thanks to Simon):

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

The = is not an operator but an assigner. You should've used this == to check if it's equal.

Comments