【问题标题】:How to check if masked input field is empty如何检查屏蔽的输入字段是否为空
【发布时间】:2016-01-06 19:04:47
【问题描述】:

我正在使用这个masked input plugin,我想检查该字段何时为空。以下是我尝试过的方法,但似乎不起作用:

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);
                }
            });

【问题讨论】:

  • id 是“phoneid”还是“Momphone”?
  • 应该是phoneid。我已经更正了代码。

标签: javascript html livevalidation


【解决方案1】:

您使用的屏蔽插件会更改 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>

    【讨论】:

      【解决方案3】:

      对我来说简单的解决方案。此代码用于检查所有输入,包括屏蔽: 输入.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);
      });
      

      【讨论】:

        【解决方案4】:

        看看我的 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');
          }
        })
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-04-23
          • 2021-09-14
          • 1970-01-01
          • 2013-10-28
          • 2020-02-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多