87,910
社区成员
发帖
与我相关
我的任务
分享
<input type="text" />
<input type="text" />
<input type="submit" value="提交" />
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;
<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>
<script type="text/javascript">
function check(f) {
if (f.txt1.value == "") { alert('txt1不能为空!'); f.txt1.focus(); return false; }
if (f.txt2.value == "") { alert('txt2不能为空!'); f.txt2.focus(); return false; }
}
</script>
</head>
<form onsubmit="return check(this)">
<input type="text" name="txt1" />
<input type="text" name="txt2" />
<input type="submit" value="提交" /></form>