未输入时属性value的默认值--js学习之路" type="hidden"/>

未输入时属性value的默认值--js学习之路


在百度ife刷题是自己的一个错误引发了我对<input type="text"/>的学习。

先贴代码:

 

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>example</title>
  </head>
<body>
  <label for="weather_input">请输入北京今天空气质量:<input id="weather_input" type="text"/></label>
  <button id="confirm_button">确认</button>
  <p>你输入的值是:<span id="value_show">尚未输入</span></p>
<script type="text/javascript">
window.onload=function(){
  var button=document.getElementById("confirm_button");
  var span=document.getElementById("value_show");
  var input=document.getElementById("weather_input").value;
  button.onclick=function(){
  span.innerHTML=input;
}
}
</script>
</body>
</html>

 

这段代码语法上是正确的,不过逻辑上是有问题的:var input=document.getElementById("weather_input").value;该语句中input获取了input输入框的默认值,之后再触发button.onclick时,input的值无法即时更新,也就无法达到程序即时显示效果。

这引出了今天探讨的问题:在<input type="text"/>中未规定value的初始值同时用户未输入时,value的默认值是什么?

null还是undefined还是""?

从var input=document.getElementById("weather_input").value看,我们可以看到document.getElementById("weather_input")这个元素节点对象是存在的,不为空,因此排除null。

至于到底是""还是undefined,我通过实践找到了答案。

 

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>example</title>
  </head>
<body>
  <label for="weather_input">请输入北京今天空气质量:<input id="weather_input" type="text"/></label>
  <button id="confirm_button">确认</button>
  <p>你输入的值是:<span id="value_show">尚未输入</span></p>
<script type="text/javascript">
window.onload=function(){
  var button=document.getElementById("confirm_button");
  var span=document.getElementById("value_show");
  alert(document.getElementById("weather_input").value===undefined);//验证是否等于undefined
  alert(document.getElementById("weather_input").value==="");//验证是否等于""
}
}
</script>
</body>
</html>

 

通过上述代码,我看到的程序运行结果是:第一个弹出框显示为false;第二个弹出框显示为true。

结论显而易见:在<input type="text"/>中未规定value的初始值同时用户未输入时,value的默认值是""。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM