<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>Document</title>
</head> <body>
<input type="text" placeholder="请输入姓名(必须是汉字)" name="xingming" id="xingming" />
<button id="btn">点击</button>
<script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
//判断是否填写姓名
$(function() {
$("#btn").click(function() {
// 第一种方法:
if ($("#xingming").val() == '') {
$("#xingming").trigger("focus");
alert("请填写姓名!");
return false;
}
// 第二种方法
// if (document.getElementsByName("xingming")[0].value == "") {
// alert("请填写姓名!");
// } });
});
</script>
</body> </html>
效果图:
第二种:
<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>Document</title>
</head> <body>
<form action="xm.php" method="post" onsubmit="return chkfrom_xm();">
<div><span>男方姓名</span>
<input type="text" name="xing1" class="input" id="xing1" />
</div>
<div><span>女方姓名</span>
<input type="text" name="xing2" class="input" id="xing2" />
</div>
<button type="submit">点击提交</button>
</form>
<script type="text/javascript">
function chkfrom_xm() {
var xing1 = document.getElementById('xing1');
var xing2 = document.getElementById('xing2');
if (xing1.value == '') {
alert('请输入男方姓名');
return false;
}
if (xing2.value == '') {
alert('请输入女方姓名');
return false;
}
return true;
}
</script>
</body> </html>
注意:这里要用submit。
效果图:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
*{margin:0; padding: 0;}
.btn{ background: #ddd; width: 100px; height: 30px; line-height: 30px; text-align: center; }
/*.red_btn{ background: red; color: #fff; width: 100px; height: 30px; line-height: 30px; text-align: center; }*/
</style>
</head>
<body>
<form>
<div>姓名:<input type="text" id="username" name="" placeholder="输入您的姓名"></div>
<div>电话:<input type="text" id="phone" name="" placeholder="输入你的手机电话"></div>
<input type="submit" name="" value="提交" id="btn" class="btn">
</form>
<script src="http://apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function sub(){
// alert(1)
var userName = $("#username");//姓名
var phone = $("#phone");//手机号码
var btn = $("#btn");//提交按钮
btn.click(function(){
//姓名
var xm = userName.val();
if(xm==""){
alert("请输入姓名");
return false;
}
//手机
var sj = phone.val();
if(sj==""){
alert("请输入手机号码");
return false;
} });
}
sub();
</script>
</body>
</html>
效果图: