首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

如何判断为空

2013-10-21 
怎么判断为空input typetext /input typetext /input typesubmit value提交 /请问下 怎

怎么判断为空


<input type="text" />
<input type="text" />
<input type="submit" value="提交" />

请问下 怎么文本框判断为空 当文本框为空的时候 按提交按钮弹窗 提交失败
[解决办法]

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$(":submit").click(function(){
$("input[type=text]").each(function(i,j){
if($(this).val()==""){
alert("第"+(parseInt(i)+1)+"个文本框为空提交失败");
return false;
}

});
});
})
</script>

[解决办法]

var txtValue = document.getElementById("txt").value;
txtValue = txtValue.replace(/^ /, "").replace(/ $/, "");  // 去除字符串起始空格和尾部空格
txtValue = txtValue.replace(/ /, ""); // 替换全角空格
if (txtValue.length == 0) { return false; // 内容为空 }
return true;

// 另一种JQUERY写法更方便
var txtValue = $("#txt").val();
if ($.trim(txtValue).length == 0) {
    return false;
}
return true;

热点排行