2

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 :/

3
  • It should be if(ninp == "") because you're already grabbing the value in the first line. Commented Aug 27, 2017 at 13:41
  • Oh exuse me that was a mistake the post is updated now Commented Aug 27, 2017 at 13:42
  • Is that the whole function because that code works as it should (it's using the first condition, not the second). Commented Aug 27, 2017 at 13:45

4 Answers 4

1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

The OP updated the question. This is no longer the case.
0

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
}

Comments

0

You can also check in this way

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.