我有以下Javascript检查字段是否为空。
function checkForm(form) {
if(this.firstname.value == "") {
alert("Please enter your First Name in the form");
this.firstname.focus();
return false;
}
}
我如何使用jQuery重写它?
答案 0 :(得分:2)
您可以使用Jquery验证执行此操作。
$(".form").validate({
rules: {
firstname: {
required: true
},
},
errorElement: 'div',
errorPlacement: function (error, element) {
var placement = $(element).data('error');
if (placement) {
$(placement).append(error);
}
else {
error.insertAfter(element);
}
}
});
答案 1 :(得分:1)
类似
var $firstName = $(this).find( "[name='firstname']" );
if ( $firstName.val().length == 0 )
{
alert("Please enter your First Name in the form");
$firstName.focus();
return false;
}
答案 2 :(得分:1)
非常简单。详情在Snippet中评论
<强>段强>
/* When any input has lost focus (ie blur)
|| and it's value is false, raise the alarm
*/
$('input').on('blur', function() {
if (!$(this).val()) {
alert('PUT SOMETHING IN THIS BOX');
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input>
&#13;