【问题标题】:Using form.submit to validate checkbox section使用 form.submit 验证复选框部分
【发布时间】:2016-03-02 10:10:58
【问题描述】:

我有一个名称传递给控制器​​的表单,当表单为 $valid 时,我继续处理数据。这曾经与单选按钮一起使用,但是当我切换到复选框时,只有当所有复选框都被选中时,验证才会通过。我怎样才能做到这一点,选择 1 使表格有效? 代码sn-p供参考:

<form name="snippetForm" ng-submit="vm.submitForm(snippetForm)" novalidate>
    <input type="checkbox" ng-model="vm.destination.1" ng-true-value="'1'" name="location" required >
    <input type="checkbox" ng-model="vm.destination.2" ng-true-value="'2'" name="location" required >
    <input type="checkbox" ng-model="vm.destination.3" ng-true-value="'3'" name="location" required >
</form>

vm.submitForm = function(form) {
    if(form.$valid) {
        console.log('Passes only when all checkboxes from form.location are selected')
    }
}

【问题讨论】:

    标签: javascript angularjs forms checkbox


    【解决方案1】:

    我在每个复选框上添加了ng-change 表达式。如果没有选中复选框,表达式将设置表单无效。

    <form name="snippetForm" ng-submit="vm.submitForm(snippetForm)" novalidate>
        <input type="checkbox" ng-model="vm.destination1" ng-true-value="'1'" name="location" ng-change="{{(!vm.destination1 && !vm.destination2 && !vm.destination3) ? (snippetForm.$valid = false) : (snippetForm.$valid = snippetForm.$valid)}}" >
        <input type="checkbox" ng-model="vm.destination2" ng-true-value="'2'" name="location" ng-change="{{(!vm.destination1 && !vm.destination2 && !vm.destination3) ? (snippetForm.$valid = false) : (snippetForm.$valid = snippetForm.$valid)}}" >
        <input type="checkbox" ng-model="vm.destination3" ng-true-value="'3'" name="location" ng-change="{{(!vm.destination1 && !vm.destination2 && !vm.destination3) ? (snippetForm.$valid = false) : (snippetForm.$valid = snippetForm.$valid)}}" >
    </form>
    

    【讨论】:

    • 感谢您的帮助,但使用复选框会产生副作用,因此我必须为元素指定不同的 ng-model 名称。现在的方式,选择一个会将所有复选框标记为已选中
    • 嗯,是的,我从收音机开始,直到发现可以选择超过 1 个位置,所以我需要使用复选框 - 现在不允许我验证表单,该怎么办?
    • 抱歉,我认为这不是一个好的解决方案。如果我有超过 3 个复选框,这个三元组看起来很荒谬。另外,选择 1 个复选框将强制表单变为有效,即使其他输入字段中有错误。我认为这可以通过修改内置验证器来解决,但对于我现在来说这太麻烦了。如果我有什么想法会告诉你。
    • @lukiwolski 没有超过 3 个复选框的输入字段。另外我更新了代码
    猜你喜欢
    • 1970-01-01
    • 2017-12-24
    • 2020-07-12
    • 2013-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    相关资源
    最近更新 更多