当前位置: 代码迷 >> Java Web开发 >> 判断字段是否为空解决思路
  详细解决方案

判断字段是否为空解决思路

热度:3303   发布时间:2013-02-25 21:20:10.0
判断字段是否为空
HTML code
 <s:form action="loginTea"> 用   户<input type="text" name="sxteacher.teaUsername" />   密   码<input type="password" name="sxteacher.teaPassword" /> <input name="submit" type="submit" value="登录" style="width:100px"/> </s:form>


上面的这段代码我想用js判断那两个属性是否为空,如果为空就提示某字段为空,该怎么做


------解决方案--------------------------------------------------------
form里加个属性name="postForm"吧
HTML code
<script type="text/javascript">        function check()        {            if(document.postForm.username.value == "") {                alert("不能为空");                return false;            }            if (document.postForm.password.value.length > 500) {                alert("不能为空");                return false;            }        }        </script>
------解决方案--------------------------------------------------------
JS不能判断控件值是否为null,只能判断类似于empty的概念,也就是空串。

首先要让你的控件能够被访问,所以最好指定ID:
<input id="username" type="text" name="sxteacher.teaUsername" />

然后可以编辑函数来实现:
function check() {
var domUser = document.getElementById("username");
if (!domUser.value) {
alert("请填写用户名!");
return false;
}
}

最后是看把这个函数加到哪里去,一般是 submit事件,类似于:
<form ...... onsubmit="return check();">



------解决方案--------------------------------------------------------
HTML code
<script type="text/javascript">        function check()        {            if(document.postForm.username.value == "") {                alert("不能为空");                return false;            }            if (document.postForm.password.value == "") {                alert("不能为空");                return false;            }        }</script>
------解决方案--------------------------------------------------------
探讨

form里加个属性name="postForm"吧
HTML code

<script type="text/javascript">
function check()
{
if(document.postForm.username.value == "") {
alert("不能为空");
……

------解决方案--------------------------------------------------------
HTML code
<script type="text/javascript">        function check()        {            if(document.postForm.username.value == "") {                alert("不能为空");                return false;            }            if (document.postForm.password.value.length > 500) {                alert("不能为空");                return false;            }            document.postForm.submit() ;        }        </script> <s:form id="postForm" action="loginTea"> 用   户<input type="text" name="sxteacher.teaUsername" />   密   码<input type="password" name="sxteacher.teaPassword" /><input name="submit" type="button" onclick="check();" value="登录" style="width:100px"/> </s:form>
  相关解决方案