提问人:Никита Кабанов 提问时间:11/14/2023 更新时间:11/15/2023 访问量:38
用于在表单中输入数字的掩码
mask for entering numbers in the form
问:
wordpress上有一个联系表格,这个jQuery使发送按钮在填写数据之前不可用,如何制作掩码,填写时的最小位数,我使用2个字段,name和tel
jQuery(document).ready(function($){
$('.wpcf7-form').each(function () {
let form = $(this);
$(form).find('input[type=submit]').prop('disabled', true);
});
$(document).on('keyup', '.wpcf7-form input', function () {
let form = $(this).parents('.wpcf7-form');
let err = 0;
$(form).find('.wpcf7-form-control').not('input[type=submit]').each(function () {
if ($(this).val() == '') {
err++;
}
})
if (err > 0) {
$(form).find('input[type=submit]').prop('disabled', true);
}else{
$(form).find('input[type=submit]').prop('disabled', false);
}
})
})
目前还没有任何进展
答:
0赞
tacoshy
11/14/2023
#1
只需用作电话号码的输入即可。然后将属性添加到该输入中。 只有在填写了所有必填字段后,才允许提交表格。如果未填写其中一个必填字段,则默认情况下表单将引发错误:<input type="tel">
required
required
<form>
<label for="name">Name: </label>
<input type="text" id="name" required>
<br>
<label for="phone">Telephone: </label>
<input type="tel" id="phone" required>
<br>
<input type="submit">
</form>
1赞
SKJ
11/15/2023
#2
为了确保在循环中使用正确的元素,您宁愿使用 var 并使用 .当您在事件中循环时,甚至更多。$(this)
要获得输入文本的正确值,您需要使用修剪函数来删除空白区域。
我注释了我的代码。
jQuery(document).ready(function($){
$('.wpcf7-form').each(function () {
let form = $(this);
$(form).find('input[type=submit]').prop('disabled', true);
});
$(document).on('keyup', '.wpcf7-form input', function () {
let form = $(this).parents('.wpcf7-form');
// set var to false by default
let err = false;
// lets loops on all input not type submit in .wpcf7-form
$('.wpcf7-form input:not([type=submit])').each(function () {
var $thisInput = $(this); // set a var with $(this) to be sure to get the right element
var thisInputVal = $.trim($thisInput.val()); // get the val and remove empty space
var thisInputName = $thisInput.attr("name"); // get name attribute of current input
var thisInputLength = thisInputVal.length; // get the length of current input
//console.clear();
//console.log(thisInputName + " - " + thisInputVal + " - " + thisInputLength); // debug
// if we find element that is empty then we set err var to true
// or if length of telephone is < 10 then we set err var to true
if (thisInputVal == '' || thisInputName === "telephone" && thisInputLength < 10) {
err = true;
}
})
//console.log(err); // debug
if (err === true) {
$(form).find('input[type=submit]').prop('disabled', true);
} else {
$(form).find('input[type=submit]').prop('disabled', false);
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="wpcf7-form">
<label for="name">Name: </label>
<input type="text" id="name" name="name">
<br>
<label for="telephone">Telephone: </label>
<input type="tel" id="phone" name="telephone">
<br>
<input type="submit">
</form>
评论