gpt4 book ai didi

javascript - 带有包含文本字段的 "other"选项的 AngularJS 单选按钮组

转载 作者:行者123 更新时间:2023-11-30 12:50:38 25 4
gpt4 key购买 nike

我有一个包含三个单选按钮的表单。第三个单选按钮是“其他”,有一个文本字段,用户可以在其中输入内容。我可以通过将“required”属性添加到单选按钮的输入元素来使单选按钮成为必需的。但是,当且仅当选择了“其他”单选按钮时,我想让文本字段成为必填项。我怎样才能做到这一点?

<p>
Program:
<label><input type="radio" ng-model="form.Program" name="Program" value="option 1" required /> option 1</label>
<label><input type="radio" ng-model="form.Program" name="Program" value="option 2" required /> option 2</label>
<label><input type="radio" ng-model="form.Program" name="Program" value="other" required /> other</label>
<input type="text" ng-model="form.OtherProgram" ng-disabled="form.Program != 'other'" name="Program_Other" />
</p>

我想做的另一件事是以某种方式确保如果未选择“其他”,则 $scope.form.OtherProgram 为空,同时将文本留在屏幕上,以便在重新选择时用户不必重新输入文本字段中的内容。

最佳答案

您可以使用 ng-required。有点像

<input type ="text" ng-required ="form.Program != 'other'">

应该可以。

关于您的其他问题,您必须为 form.OtherProgram 使用一些 Controller 逻辑和某种临时变量,例如使用 $watch。

$scope.$watch('form.Program', function(mVal){
if (angular.isUndefined($scope.form)) return;

if(mVal === 'other'){
$scope.form.OtherProgram = $scope.tmVar;
} else {
if($scope.form.OtherProgram !== null){
$scope.tmVar = $scope.form.OtherProgram;
$scope.form.OtherProgram = null;
}
}
});

笨蛋:http://plnkr.co/edit/npvUXpRhB5MYJOstwd88?p=preview

关于javascript - 带有包含文本字段的 "other"选项的 AngularJS 单选按钮组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21078146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com