如何检查掩码输入框是否为空。

4
我将使用这个掩码输入插件,并希望检查字段是否为空。以下是我尝试过的代码,但似乎不起作用:

HTML

<input type="text" name="phone" id="phoneid" />

Le JavaScript:

$("#phoneid").mask("999-999-9999");

这段代码无法运行

            $("#phoneid").keyup(function(){
                if($("#phoneid").val().length == 0){
                    alert(111);
                }
            });

1
这个id是“phoneid”还是“Momphone”? - Pointy
应该是 phoneid。我已经纠正了代码。 - mpora
4个回答

5

您正在使用的遮罩插件会改变 input 元素的值。

当该元素为空时,其值为 ___-___-____

在检查该值的长度时,您可以简单地去掉 _/- 字符:

$("#phoneid").on('keyup', function() {
  if (this.value.replace(/[_-]/g, '').length === 0) {
    alert('Empty');
  }
});

或者,您也可以检查该值是否只包含_/-字符:

$("#phoneid").on('keyup', function() {
  if (/^[_-]+$/.test(this.value)) {
    alert('Empty');
  }
});

2
我们可以通过再次使用“9999999999”进行掩码处理来获取未掩码值的类型,即没有破折号,然后进行如下比较:

$(document).ready(function(){
  $("#phoneid").mask("999-999-9999");
  
  $("#phoneid").keyup(function(){
     if($("#phoneid").mask("9999999999").val().length == 0){
         alert(111);
     }
     $("#phoneid").mask("999-999-9999");
   });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<script src="https://raw.githubusercontent.com/digitalBush/jquery.maskedinput/1.4.1/dist/jquery.maskedinput.min.js"></script>

<input type="text" name="phone" id="phoneid" />
<button id="test">Test</button>


1

对我来说很简单的解决方案。这段代码用于检查包括掩码在内的所有输入:inputs.val() == ""

.on('blur', '.form__input', function(e) {
    var inputs = $(this).find('input,textarea,select');
    setTimeout(function(){
        if (inputs.val().length == 0 || inputs.val() == ""){
            alert('Empty');
        }
    },100);
});

0
看看我的 Codepen:https://codepen.io/ngocquydhtn/pen/YzwVMKR
    $(document).ready(function() {
var phoneMask = IMask(
  document.getElementById('phoneid'),
  {
    mask: '0000-000-000',
    lazy: false, 
    placeholderChar: '_'
  })
$("#phoneid").keyup(function(){
  if(this.value.replace(/[_-]/g, '').length==10){
    $(".btn").removeAttr('disabled');
  }
  else{
    $(".btn").attr('disabled','true');
  }
})
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接