如果值为空

时间:2014-05-07 23:26:15

标签: javascript html

我有一些代码可以将用户输入保存到本地存储中,然后将值打印到选定的ID中。

function saveData() { 
var input = document.getElementById("saveServer");
localStorage.setItem("server", input.value);  
console.log(localStorage.getItem("server"));
document.getElementById("yourname").innerHTML ="Okay  " + (localStorage.getItem("server")) + "  Let's get started! Push the button on the right to begin the story!"  ;   
}

如果输入字段为空,我该怎么做才会产生一个声明,通知用户输入他们的名字。

我已经查看了if和else语句,但我尝试的任何内容似乎都没有效果。

编辑:

想出来了!

if (saveServer.value == "")  {
document.getElementById("yourname").innerHTML = "Please input your name";
} 

else {   
document.getElementById("yourname").innerHTML ="Okay  " + (localStorage.getItem("server")) + "  Let's get started! Push the button on the right to begin the story!"  ;   
}

2 个答案:

答案 0 :(得分:0)

添加条件以检查输入是否为空。

function saveData() { 
var input = document.getElementById("saveServer").value;
if(input ==="") alert("Enter saveServer");
else{
  localStorage.setItem("server", input.value);  
  console.log(localStorage.getItem("server"));
  document.getElementById("yourname").innerHTML ="Okay  " + (localStorage.getItem("server")) + "  Let's get started! Push the button on the right to begin the story!"  ;   
  }
}

答案 1 :(得分:0)

像这样:

function saveData() {
    var input = document.getElementById("saveServer");
    localStorage.setItem("server", input.value);
    var serverValue = localStorage.getItem("server");
    if (!serverValue) {
        document.getElementById("error").innerHTML = "Oh dear! Nothing was found";
    }
    document.getElementById("yourname").innerHTML = "Okay  " +     (localStorage.getItem("server")) + "  Let's get started! Push the button on the right to begin the story!";
}

小提琴: http://jsfiddle.net/KyleMuir/LhyXr/