【问题标题】:Angular JS dropdown list select "Others" option and Others input become mandatoryAngular JS下拉列表选择“其他”选项,其他输入成为强制性
【发布时间】:2017-05-25 22:32:44
【问题描述】:

我正在尝试添加带有“其他”选项的下拉列表。如果用户选择“其他”,其他(请注明)输入框将变为必填项。我应该如何验证这个案例?现在我添加了 Javascirpt 代码来验证这一点。有没有像“请说明其他原因”这样的做法?

<form name="myForm">

    <div ng-app="myApp" ng-controller="myCtrl">

    Reason : <select ng-model="reason" ng-options="x for x in names" required></select>    <span ng-show="myForm.reason.untouched">The reason is required.</span>

<p>Others (specify): <input type="text" ng-model="others"></p>


    </div>
    </form>




    <script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
        $scope.names = ["reason1", "reason2", "reason3","Others"];

$scope.addItem = function () {

     if ($scope.reason == "Others" && !$scope.others)
     {
         window.alert("Please specify others");
     }

     if($scope.others && $scope.reason!='Others')
     {
         window.alert("Please select reason others");
     }


    });
    </script>

【问题讨论】:

  • &lt;input type="text" ng-model="others" ng-required="reason === 'Others'" /&gt;
  • 嗨,JB。谢谢你。它正在工作。

标签: angularjs dropdown angularjs-validation


【解决方案1】:

Angular 有一个 ng-required 属性,允许您有条件地设置它。

<form name="myForm">

<div ng-app="myApp" ng-controller="myCtrl">

Reason : <select ng-model="reason" ng-options="x for x in names" required>
</select>    <span ng-show="myForm.reason.untouched">The reason is required.
</span>

<p>Others (specify): <input type="text" ng-model="others" ng-required="reason == 'Others'"></p>


</div>
</form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    相关资源
    最近更新 更多