1

in jsp i am writing java script. Please help me how to do null check in javascript? i have drop down list. onchange some action should happen. pleae find below code.

<select onchange="openPage(this.value)">

here some times this.value can be null. simply i need to do null check.when it is not null then only it should call openPage() method. please help me how to solve?

Thanks!

2
  • if(this.value != null) . sorry code is missing. Commented Oct 17, 2011 at 12:19
  • <select onchange="javascript:if(this.value !== null) openPage(this.value)"> ? Commented Oct 17, 2011 at 12:22

3 Answers 3

3

the simplest way to do this, and it covers cases where the value is an empty string, false, null, zero or undefined is:

if(!this.value) {
   //this will only execute if this.value is null, undefined, zero, empty string or false
}

Hope that helps. Obviously this isn't a good idea when it comes to working with boolean values (where you genuinely expect true or false values), but for 99% of the time it's great :)

Sign up to request clarification or add additional context in comments.

4 Comments

!'' is returns true but you said for empty strings too ?
Argh, Boolean logic fail! What I meant was it will only execute if this.value is null, undefined etc. The code is correct, the comment was not. Updated answer to reflect your observation. Thanks
I always hate to check null,undefined and empty strings together in javascript :). It is better to encapsulate these checks in a function.
I just like to embrace the truthy/falsey nature of JavaScript. For most instances empty strings, null or undefined require similar handling - consider string.IsNullOrEmpty or string.IsNullOrWhitespace in .NET. So I find it makes sense to group the logically as above, keeps your code quite terse as well
1
(this.value == undefined)

Do check as above

1 Comment

i was going to say, i've never seen the is operator in JS. Am i missing something here??
0

Try using this:

if(this.value != null)

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.