【问题标题】:on keyup validation is working but on keypress its not working在 keyup 验证正在工作,但在 keypress 上它不起作用
【发布时间】:2016-04-27 10:39:23
【问题描述】:

输入框需要以下验证:

1) 长度输入框最多取3个整数长度值(不允许小数)

2) 高度输入框应取 3 个整数和小数,最多 2 位 它第一次工作正常,但单击 + 按钮后(打开新行 1 附近)相同的输入字段正在打开,但现在:在新即使我对输入框使用相同的类,框验证也不起作用,即新添加的输入框采用任意数量的数字和字符。

在 keyup 功能中它正在工作,但是如果用户按下任何键它对新打开的行不起作用,那么在这两种情况下如何使其在 keypress 上工作;按键验证有效,但按键无效

var app = angular.module('Calc', []);
 var inputQuantity = [];
    $(function() {
      $(".form-control").each(function(i) {
        inputQuantity[i]=this.defaultValue;
         $(this).data("idx",i); // save this field's index to access later
      });
      $(".form-control").on("keyup", function (e) {
        var $field = $(this),
            val=this.value,
            $thisIndex=parseInt($field.data("idx"),10); // retrieve the index
//        window.console && console.log($field.is(":invalid"));
          //  $field.is(":invalid") is for Safari, it must be the last to not error in IE8
        if (this.validity && this.validity.badInput || isNaN(val) || $field.is(":invalid") ) {
            this.value = inputQuantity[$thisIndex];
            return;
        } 
        if (val.length > Number($field.attr("maxlength"))) {
          val=val.slice(0, 5);
          $field.val(val);
        }
        inputQuantity[$thisIndex]=val;
      });      
    });
app.controller('Calc_Ctrl', function ($scope, $http) {
     $scope.choices = [{id : 'choice1', l2 : 0, b2 : 0}];
     $scope.areas = [{id : 'choice2', total : 0}];

     $scope.addNewChoice = function () {
          var newItemNo = $scope.choices.length + 1;
          $scope.choices.push({
               'id' : 'choice' + newItemNo, l2 : 0, b2 : 0
          });
     };
     $scope.removeChoice = function () {
          var lastItem = $scope.choices.length - 1;
          if (lastItem !== 0) {
               $scope.choices.splice(lastItem);
          }
     };
});
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="newscript.js"></script>

<body>
  <div ng-app="Calc" ng-controller="Calc_Ctrl">
               <div  data-ng-repeat="choice in choices" class="col-md-12 col-sm-12 col-xs-12 bottom-line no-gap">
                              <h6>Open New Row {{$index + 1}} 
                                   <button type="button" class="btn btn-default pull-right btn-right-gap  btn-red" aria-label="Left Align"  ng-click="addNewChoice()" style="margin-top: -5px;" id="plus_icon">
                                        <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
                                   </button>

                              </h6> 
                              <div class="row walls top-gap">

                                   <div class="form-group col-md-3 col-sm-3 col-xs-12">
                                        <label for="length">Length :</label>
                                        <input type="number" class="form-control text-red bold" id="length"  ng-model="choice.l2"  min="0" max="999" maxlength="6" step="0.00">
                                   </div>
                                   <div class="form-group col-md-3 col-sm-3 col-xs-12">
                                        <label for="height">Height :</label>
                                        <input type="number" class="form-control text-red bold" id="height"   ng-model="choice.b2"  min="0" max="999" maxlength="6" step="0.01">
                                   </div>
                                 
                                   <button type="button" class="btn btn-default pull-right btn-red" aria-label="Left Align"  ng-click="removeChoice()" id="minus_icon">
                                   </button>
                              </div>

                         </div>
  </div>
</body>

</html>

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    要为所有字段触发 keyup 事件,我们需要稍微更改侦听器的定义,选择器 .form-control 应在 on() 内定义为子选择器和 document 作为主选择器:

    $(document).on("keyup",".form-control", function (e) {
    // listener code
    });
    

    keypress 事件的行为与 keyup 事件不同。 keypress 会在每个按键被按下并且在字段中设置值之前触发。而 keyup 事件会在每个键被释放并且在值被设置之后触发field.So 相同的方法不适用于 keypress

    var app = angular.module('Calc', []);
     var inputQuantity = [];
        $(function() {
          $(".form-control").each(function (i) {
                inputQuantity[i] = this.defaultValue;
                $(this).data("idx", i); // save this field's index to access later
            });
            $(document).on("keypress", ".form-control", function (e) {
                if (e.charCode!=0){
                var $field = $(this),
                val = this.value + '' + String.fromCharCode(e.charCode), pattern;
                if (this.step == 0.00)
                    pattern = /[^0-9]/
                else
                    pattern = /[^0-9.]/
                if (val > parseInt(this.max, 10) || pattern.test(val) || (val.match(/\./) && (val.match(/\./g).length > 1 || val.replace(/\d+\./, '').length > 2))) {
                    e.preventDefault();
                }
               }
            });
            $(document).on("keyup",".form-control", function (e) {
                var $field = $(this),
                    val=this.value,
                    $thisIndex=parseInt($field.data("idx"),10); 
                if (parseInt(val,10) > parseInt(this.max, 10) ) {
                    this.value = inputQuantity[$thisIndex];
                    return;
                } 
                if (val.length > Number($field.attr("maxlength"))) {
                    val=val.slice(0, 5);
                    $field.val(val);
                }
                inputQuantity[$thisIndex]=val;
            });      
        });
    app.controller('Calc_Ctrl', function ($scope, $http) {
         $scope.choices = [{id : 'choice1', l2 : 0, b2 : 0}];
         $scope.areas = [{id : 'choice2', total : 0}];
    
         $scope.addNewChoice = function () {
              var newItemNo = $scope.choices.length + 1;
              $scope.choices.push({
                   'id' : 'choice' + newItemNo, l2 : 0, b2 : 0
              });
         };
         $scope.removeChoice = function () {
              var lastItem = $scope.choices.length - 1;
              if (lastItem !== 0) {
                   $scope.choices.splice(lastItem);
              }
         };
    });
    <!DOCTYPE html>
    <html>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script src="newscript.js"></script>
    
    <body>
      <div ng-app="Calc" ng-controller="Calc_Ctrl">
                   <div  data-ng-repeat="choice in choices" class="col-md-12 col-sm-12 col-xs-12 bottom-line no-gap">
                                  <h6>Open New Row {{$index + 1}} 
                                       <button type="button" class="btn btn-default pull-right btn-right-gap  btn-red" aria-label="Left Align"  ng-click="addNewChoice()" style="margin-top: -5px;" id="plus_icon">
                                            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
                                       </button>
    
                                  </h6> 
                                  <div class="row walls top-gap">
    
                                       <div class="form-group col-md-3 col-sm-3 col-xs-12">
                                            <label for="length">Length :</label>
                                            <input type="text" class="form-control text-red bold" id="length"  ng-model="choice.l2" min="0" max="999" maxlength="6" step="0.00">
                                       </div>
                                       <div class="form-group col-md-3 col-sm-3 col-xs-12">
                                            <label for="height">Height :</label>
                                            <input type="text" class="form-control text-red bold" id="height"   ng-model="choice.b2" min="0" max="999" maxlength="6" step="0.01">
                                       </div>
                                     
                                       <button type="button" class="btn btn-default pull-right btn-red" aria-label="Left Align" ng-click="removeChoice()" id="minus_icon">
                                       </button>
                                  </div>
    
                             </div>
      </div>
    </body>
    
    </html>

    【讨论】:

    • 它很好,有什么方法可以对按键进行同样的操作,如果我们删除了按键也可以,但是当用户输入它必须采用的值时。
    • ,是的,因为只有用户才能输入正确的值
    • 根据您的代码,我将按键替换为按键,但在某些情况下它不起作用,如果可能,请提供一些解决方案?
    • 它的帮助!!!但是在高度框中输入 3 个整数值后,它不取任何十进制值,它必须取 2 个十进制值,所以知道如何允许它也取十进制值。
    • 我用的是chrome浏览器
    猜你喜欢
    • 2021-12-08
    • 2018-07-17
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2016-10-28
    • 2015-11-22
    • 1970-01-01
    相关资源
    最近更新 更多