如何将输入键作为输入选项卡并提交如果在angularjs中找到按钮?

时间:2017-06-06 07:15:01

标签: javascript jquery angularjs

我有一个视图,其中有两个按钮。一个用于保存,另一个用于更新:我想使用回车键作为选项卡。如果它到达最后一个输入并找到按钮,则表单将被提交(将触发ng-click功能)。是否可以使用两个按钮,或者我应该只依靠一个按钮?

我试过了:

     $('#truckform input ,#truckform button').on("keypress", function(e) {
                 // ENTER PRESSED
                if (e.keyCode == 13) {

                    console.log('tag')
                   // FOCUS ELEMENT
                    var inputs = $(this).parents("form").eq(0).find(":input");
                    var idx = inputs.index(this);
console.log(idx)

                    console.log(inputs.length)
                    if (idx == inputs.length - 1) {
                        inputs[0].select()
                    } else {
                        inputs[idx + 1].focus(); //  handles submit buttons
                        inputs[idx + 1].select();
                    }
                    return false;
                }
            });

当按钮获得焦点时,我在控制台中给出错误:

Uncaught TypeError: inputs[(idx + 1)].select is not a function
at HTMLInputElement.<anonymous> (truckEntry.js:56)
at HTMLInputElement.dispatch (jquery-2.2.3.min.js:3)
at HTMLInputElement.r.handle (jquery-2.2.3.min.js:3)

但是在错误之后,会触发saveData()函数。但是在更新模式下,updateData()不会被触发,并且错误将一直保持到我按Enter键为止。我该如何制作它的功能?有什么建议吗?   我的观点:

  <form  name="truckform" id="truckform" novalidate>
               <table id="truckformTbl">
                   <tr>
                       <td class="text-center" colspan="6">
                           <h4 class="ok"> Truck Entry/Exit Form</h4>
                       </td>
                   </tr>
                    <tr ng-hide="hideManifestDetailsInput">
                        <th>Manifest No : </th>
                        <td>
                            <input type="text" ng-pattern='/^[0-9]{1,10}[/]{1}([0-9]{1,2}|[(A|a)]{1})$/' required="required" ng-disabled="disbleManifestNoInpForEditMode"  ng-model="ManifestNo" name="ManifestNo" id="Manifest_no" class="form-control input-sm" placeholder="Manifest No.">
                            <span class="error" ng-show='truckform.ManifestNo.$error.pattern'>
                                Input like: 256/12 Or 256/A
                            </span>
                            <span class="error" ng-show="submitted && !ManifestNo && !truckform.ManifestNo.$error.pattern">
                              Manifest No is required
                            </span>

                            <span class="error" ng-show="truckExceedInManifest">Manifest is full</span>
                        </td>
                        <th>&nbsp; Manifest Date :</th>
                        <td>
                            <input type="text"  ng-model="manifest_date" required="required" name="manifest_date" id="manifest_date" class="form-control datePicker input-sm" placeholder="Manifest date">

                            <span ng-show="submitted && !manifest_date" class="error">Select a date</span>
                        </td>
                        <th>&nbsp;Goods Name :</th>

                        <td style="width: 15em; vertical-align: top" rowspan="8">
                           {{-- <select class="form-control input-sm" name="goods_id" ng-model="goods_id"
                                    ng-options="good.id as good.id +'-'+good.cargo_name group by good.category for good in allGoodsData ">

                                <option value="" selected="selected">Select Goods Name</option>
                            </select>
                            <span class="error" ng-show="truckform.goods_id.$dirty && truckform.goods_id.$touched && !goods_id ">
                             Select at least one goods
                            </span>--}}


                            <tags-input ng-model="goods_id"
                                        display-property="cargo_name"
                                        placeholder="Add New Item"
                                        replace-spaces-with-dashes="false"
                                        add-from-autocomplete-only="true"
                                        on-tag-added="tagAdded($tag)"
                                        on-tag-removed="tagRemoved($tag)">

                                <auto-complete source="loadGoods($query)"
                                               min-length="0"
                                               debounce-delay="0"
                                               max-results-to-show="10">

                                </auto-complete>

                            </tags-input>
                            <span ng-show="submitted && !goods_id ||goods_id.length==0" class="error">Choose at least one goods!</span>
                        </td>
                    </tr>

<tr>
    <td colspan="4">&nbsp;</td>
</tr>
                    <tr>
                        <th>Truck Type :</th>
                        <td>
                            <input type="text" ng-model="truck_type" name="truck_type" id="truck_type" class="form-control input-sm" value="{{old('truck_type')}}"  placeholder="Truck Type">
                            <span class="error" ng-show="submitted && !truck_type">
                             Truck Type is required
                            </span>
                        </td>

                        <th>&nbsp; Truck No :</th>
                        <td>
                            <input type="number" min="1" required="required" ng-model="truck_no" name="truck_no" id="truckNo" class="form-control input-sm" placeholder="Truck No" value="{{old('truck_no')}}">
                            <span class="error" ng-show="submitted && !truck_no">
                             Truck No is required
                            </span>
                        </td>

                    </tr>

                    <tr>
                        <td colspan="4">&nbsp;</td>
                    </tr>

                    <tr>
                        <th>Driver Card No :</th>
                        <td>
                            <input type="number" ng-model="driver_card" name="DriverCardNo" id="DriverCardNo" class="form-control input-sm" placeholder="Driver Card No." value="{{old('DriverCardNo')}}">

                            <span class="error" ng-show="submitted && !driver_card">
                             Driver Card No. is required
                            </span>
                        </td>


                        <th> &nbsp;Weight Bridge:</th>
                        <td>
                            <label class="radio-inline">
                                <input type="radio" name="fff" ng-init="weightment_flag=1"  ng-model="weightment_flag" ng-checked="true"  value="1">Yes
                            </label>
                            <label class="radio-inline">
                                <input type="radio"  ng-model="weightment_flag"  value="0" >No
                            </label>
                        </td>



                    </tr>
                   <tr>
                       <td colspan="4">&nbsp;</td>
                   </tr>

                   <tr>
                       <th> &nbsp;Driver Name :</th>
                       <td style="width: 15em;">
                           <input type="text" ng-model="driver_name" name="DriverName" id="driverName" class="form-control input-sm" placeholder="Driver Name" value="{{old('DriverName')}}">
                           <span class="error" ng-show="submitted && !driver_name">
                             Driver Name is required
                            </span>
                       </td>
                   </tr>
                    <tr>
                        <td colspan="3"></td>

                        <td colspan="1" class="text-center">
                            <br>
                            <button type="button" ng-click="saveData(truckform)" ng-hide="updateBtn" class="btn btn-primary btn-block center-block">
                                <span class="fa fa-download"></span>
                                Save
                            </button>
                            <button type="button" ng-click="updateData(truckform)" ng-show="updateBtn"  class="btn btn-primary center-block">
                                <span class="fa fa-download"></span>
                                Update
                            </button>
                        </td>
                        <td colspan="2"> </td>
                    </tr>

                   <tr>
                       <td colspan="2"></td>
                       <td class="text-center" colspan="3">

                           <div id="success" class="col-md-12 alert alert-success" ng-show="successMsg">
                               Successfully @{{ successMsgTxt }}!
                           </div>

                           <div id="error" class="col-md-12 alert alert-warning" ng-show="errorMsg">
                                @{{ errorMsgTxt }}!
                           </div>
                       </td>
                       <td colspan="1"> </td>
                   </tr>
                </table>
                </form>

2 个答案:

答案 0 :(得分:1)

在这里你不需要为按键绑定按键事件,默认情况下在表格中如果有按钮,如果按下回车键,它将触发第一个按钮的点击事件, 如果您将按钮的类型设置为提交,并且当您在任何输入内部时按Enter键,则会自动触发表单提交。示例如下所示。

我编辑了我的原始答案,现在按下回车键时它就像标签一样。这是工作fiddle

<body class="container" ng-app="myApp">
<div ng-controller="myCtrl">
    <form name="truckForm" ng-submit="submit(truckForm.$valid)" class="form-horizontal container" enter-to-tab>
        <div class="form-group">
            <label for="firstname">First Name</label>
            <input type="text" name="firstname"/>
        </div>
        <div class="form-group">
            <label for="lastname">Last Name</label>
            <input type="text" name="lastname"/>
        </div>
        <div class="form-group">
            <label for="email">Email</label>
            <input type="email" name="email"/>
        </div>
        <div class="form-group">
            <label for="password">Password</label>
            <input type="password" name="password"/>
        </div>
        <div class="form-group">
            <label for="confirm_password">Confirm Password</label>
            <input type="confirm_password" name="confirm_password"/>
        </div>
        <button type="submit" class="btn btn-default">{{btnFlag}}</button>
    </form>
</div>
</body>

并在您的控制器中

    angular.module('myApp', [])
        .controller('myCtrl', myCtrl)
        .directive('enterToTab', enterToTab);

    myCtrl.$inject = ['$scope'];

    function myCtrl($scope) {
        $scope.updateBtn = true;
        $scope.submit = submit;

        function submit(valid) {
            console.log('hi', valid);
            if ($scope.updateBtn && valid) {
                updateData(/* your params if any */);
            } else if (valid) {
                saveData(/* your params if any */);
            }
        }

        function saveData(/* your params if any */) {
            console.log('save');
            // do your save action here
        }

        function updateData(/* your params if any */) {
            console.log('update');
            // do your update action here
        }
    }


    function enterToTab() {
        return {
            restrict: 'A',
            link: function(scope, attrs, element) {
                var elm = angular.element(element.$$element[0]);
                var inputs = angular.element('input', elm);
                var length = inputs.length - 1;
                var submit = angular.element('button[type=submit]', elm);
                inputs.on('keydown', function(e) {
                    if (e.which === 13) {
                        e.preventDefault();
                        var index = inputs.index(this);
                        if (index === length && submit.length) {
                            submit.focus();
                        } else if(index === length) {
                            inputs[0].focus();
                        } else {
                            inputs[index + 1].focus();
                        }
                    }   
                })
            }
        };
    }

此处type="submit"按钮非常重要。当你开发一个angularjs应用程序时,避免像dom操作那样的任何jquery,所以我用指令的角度方式做了这个。我在{<1}}标记中添加了enter-to-tab HTML

答案 1 :(得分:0)

您可以使用回车键作为标签,如下所示:

  $('input').bind("keypress", function(e) {
     // ENTER PRESSED
    if (e.which == 13) {
        e.preventDefault();
        $(this).next().focus(); 
      }
    }
  });

小羽毛here