gpt4 book ai didi

jquery - 如何在 HTML 5 验证之前使用 jquery 验证表单

转载 作者:行者123 更新时间:2023-12-01 07:39:31 25 4
gpt4 key购买 nike

我有一个阿拉伯语表单,我尝试用两种方式验证它:html 5 和 j 查询。问题是英语 HTML 5 警报出现在阿拉伯语 j 查询警报出现之前的第一个警报中,但就我而言,我想要相反的情况并进行一些更改。我希望阿拉伯文 j 查询警报出现在第一个,并且仅当 j 查询无法阻止用户作弊时才出现 HTML 5 英语警报。提前感谢

<!DOCTYPE HTML>
<html>
<head>
<title>j query_validation</title>
<meta charset="UTF-8">
</head>

<body>
<form id="formId">
<input type="text" class="input-string" required/>
<input type="submit"/>
<p class="alert-error" style="display:
none">can't be empty</p>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script>
$('#formId').submit(function(e){
var inputValue = $('.input-string').val().length;
if(inputValue == 0)
{
$('.alert-error').show();
e.preventDefault();
}
});

</script>
</body>

</html>

最佳答案

只需将 e.preventDefault() 放在函数的开头即可。

这可以防止任何默认的表单提交行为。请记住,如果成功,请实际提交表单。

$('#formId').submit(function(e){
e.preventDefault();
var inputValue;
$('.input-string').each(function(){ // If you're checking for class, you may want to include this .each function, as many elements can have the same class. If you switch to ID, this can be removed.
inputValue += $(this).val().length;
}); // End .each

if(inputValue == 0){
$('.alert-error').show();
}
else{
$('.alert-error').hide(); // Not really necessary if you're submitting and refreshing anyway, but it lets the user know it will be submitted successfully, before the page actually refreshed.
form.submit();
}

}); // End .submit

编辑:下面附上我的完整答案,根据OP的要求,以满足评论中的进一步要求。

<!DOCTYPE HTML>
<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>j query_validation</title>
<meta charset="UTF-8">
</head>

<body>
<form id="formId">
<input type="text" class="input-string" required/>
<button id="test-button" type="button" role="button">Test Me </button>
<p class="alert-error" style="display:
none">can't be empty</p>
</form>

<script>
$('#test-button').click(function(e) {
e.preventDefault();
var inputValue = 0;
$('.input-string').each(function() { // If you're checking for class, you may want to include this .each function, as many elements can have the same class. If you switch to ID, this can be removed.
inputValue += $(this).val().length;
}); // End .each
// inputValue = 0;
if (inputValue == 0) {
$('.alert-error').each(function() {
$(this).css("display", "block");
});
} else {
$('.alert-error').each(function() {
$(this).css("display", "none"); // Not really necessary if you're submitting and refreshing anyway, but it lets the user know it will be submitted successfully, before the page actually refreshed.
});

$("#formId").submit();
}

}); // End .submit
</script>
</body>

</html>

关于jquery - 如何在 HTML 5 验证之前使用 jquery 验证表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53433961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com