Detect empty value on prompt

Viewed 41567

How to detect an empty value when user presses ok on prompt (and previously empties the prompt field)? I need to overwrite the old value with the new (empty) value. I'm doing this:

var oldVal = 'something';
var newVal = prompt("Enter new value:", oldVal);

Currently it returns null if user empties value and clicks ok.

But at the same time I need to check for null value because if user clicks 'cancel', it will return null, which I don't want as new value.

7 Answers

I have see other comment that seem like solved your problem, but I think it might can no t be the best answer or solution here is your code

if (newVal == "") {
//action
}

it might seem work, but it might probably cause a problem or a little bug, is that the user can just type two blank or white-space to bypass your code, here is my solution

If (newVal.trim() == "") {
 //action
}

When user hits OK without entering any value, it returns NaN and you can check it by isNaN() function.

Related