Detect empty value on prompt

A Bit old, but it may be worthwhile to simply include a test for the string's length in the same if() statement

if(newVal !=null & newVal.length>0){

Check both for Cancel and an empty entry.


In most browsers prompt will return null if user presses cancel, but in some (Safari, for ex.) it returns empty string. If user enters some text and presses ok, prompt will return entered text, if user pressed ok without entering text, it will return empty string.


It does not return null if the user hits OK - it will return an empty string. You are probably not testing the return value properly. If you want to test between the three different return states, you can do that like this:

var oldVal = 'something';
var newVal = prompt("Enter new value:", oldVal);
if (newVal === "") {
    // user pressed OK, but the input field was empty
} else if (newVal) {
    // user typed something and hit OK
} else {
    // user hit cancel
}

Working demo: http://jsfiddle.net/jfriend00/Kx2EK/


Your comment suggests that you're using this code to test the result:

if(!newVal || oldVal == newVal)return false;

When the user clears the field and presses OK, newVal will be "" (an empty string). !newVal will be true so you will return false. An empty string is a falsey value just like null. You need to more explicitly check for null like this:

if (newVal === null || newVal === oldVal) {
    // cancel button was hit
    // or the same value was entered
    return false;
}

Working demo of this logic: http://jsfiddle.net/jfriend00/ynwBx/

Note: I'm using === to prevent the javascript interpreter from doing any type casting as I want to only explicitly check for null.