'Detect empty value on prompt

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.



Solution 1:[1]

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.

Solution 2:[2]

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.

Solution 3:[3]

<html>
<body>    
<p>Click the button to demonstrate the prompt box.</p>    
<button onclick="myFunction()">Try it</button>    
<p id="demo"></p>    
<script>
function myFunction() {
    var answer=prompt('Reason for deletion?');
    var n = answer.length;
    if(n > 5)
    {
    document.getElementById("demo").innerHTML =
    "Hello " + answer + "! How are you today?";
    }
    else if(n == 0)
    {  
    myFunction()
    } 
}
</script>    
</body>
</html>

Solution 4:[4]

Simple to see if both cancel or ok with empty string

function valueIsSet(value)
{
    return (value && value !== "")
}

// example:

var name;
while (!valueIsSet(name) {
    name = prompt("Please enter your name");
}

alert("Welcome " + name);

Solution 5:[5]

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
}

Solution 6:[6]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kaitensatsuma
Solution 2
Solution 3 sebastian
Solution 4
Solution 5
Solution 6 Caner SAYGIN