KrisGeor
KrisGeor

Reputation: 53

How to check if an input is empty using JavaScript

Ok so I have an HTML input element

<input name="name" type="text" id="name" placeholder="Name" />

and in JavaScript I do :

var ninp = document.getElementById("name");
if(ninp.value == ""){
  do stuff
} else{
  do other stuff
}

Everytime I run the function it fires the "else" block of code I'm I doing something wrong or this isnt a correct way :/

Upvotes: 2

Views: 84

Answers (4)

Ans Bilal
Ans Bilal

Reputation: 1067

why do not you move to jquery and write

var ninp = $('#name');
if(ninp.val() =="")
{
//do stuff
}else
//otherstuff

or 
if(ninp.val().length==0)

Also keep it in mind if you are using JS form external files browser mostly do not load your updated js files. In this case I mostly use incognito mode of browser

Upvotes: 0

Suresh Sapkota
Suresh Sapkota

Reputation: 259

You can also check in this way

var ninp = document.getElementById("name").value;
if(ninp.length === 0){
  do stuff
} else {
  do other stuff
}

Upvotes: 0

KrisGeor
KrisGeor

Reputation: 53

Maybe something else in the function was breaking it but the answer was just to test for the length of the string

var ninpv = ninp.value;
if(ninpv.lenght == 0;){
do stuff
}

Upvotes: 0

Mahdi P.
Mahdi P.

Reputation: 307

In first line of your code, you have gotten value of input tag. so you have something like this:

ninp = "a string ..."

and so it is impossible to have something like ninp.value in your condition in second line.

change

if(ninp.value == ""){
do stuff
}

to

if(ninp == ""){
 do stuff
}

Upvotes: 1

Related Questions