【问题标题】:Validation messages not removed after resetting the form重置表单后未删除验证消息
【发布时间】:2015-04-20 09:32:48
【问题描述】:

我有一个 html 表单,我正在使用 Angular JS 进行验证。在这里,在提交表单后,我调用了 reset 方法,它将表单输入字段重置为默认值。

但是,当我提交并调用重置方法时,验证消息会出现在输入字段中。我使用了下面的代码。我不想在提交表单后看到验证消息。

HTML

<form name="createvalidation" role="form" class="col-lg-12" novalidate>
    <div class="form-group">

    </div>
    <div class="form-group">
        <input type="text" placeholder="Challenge name" class="form-control input-sm" name="name" ng-model="challenge.challengename" required>
        <span ng-show="(createvalidation.name.$dirty || submitted) && createvalidation.name.$error.required">Name is reqiured</span>
    </div>

    <div class="form-group">
        <textarea class="form-control input-sm" rows="2" placeholder="Write more about this challenge..." name="description" ng-model="challenge.challengedescription" required></textarea>
        <span ng-show="(createvalidation.description.$dirty || submitted) && challengecreatevalidation.description.$error.required">Description is reqiured</span>
    </div>
</form>
<div>

    <button type="button" ng-click="createChallenge()">Create</button>
</div>

JS 代码

 $scope.createChallenge = function() {
     //get the field and store in db
     $scope.resetForm();
 }
 $scope.master = {};
 $scope.resetForm = function() {

     $scope.challenge = angular.copy($scope.master);
     $scope.createvalidation.$setPristine();
 }

【问题讨论】:

标签: javascript jquery html angularjs forms


【解决方案1】:

您似乎是从 resetForm 函数中复制表单的原始状态。这意味着它只会在调用 resetForm 时拥有表单的版本。相反,也许您应该在表单设置和原始时进行该副本。

【讨论】:

【解决方案2】:
$scope.createChallenge = function() {
  //get the field and store in db
 $scope.resetForm();
 }

 $scope.master = {};
 $scope.resetForm = function() {
 $scope.submitted = false; //Try adding this
 $scope.challenge = angular.copy($scope.master);
 $scope.createvalidation.$setPristine();

}

【讨论】:

  • 需要描述
  • 该行有错误。您需要更改为 createvalidation.description.$error.required
  • 乐于助人。 createvalidation.description.$error.required 是问题吗?
  • 不,我的代码中已经包含该行,但是在这里复制时我错误地留下了该行。 $scope.submitted = false,解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 2018-05-30
  • 2018-04-19
  • 1970-01-01
  • 1970-01-01
  • 2020-11-14
  • 2023-03-22
  • 2018-05-30
  • 2019-06-11
相关资源
最近更新 更多