【问题标题】:How to get the value of checkbox which has been checked如何获取已选中的复选框的值
【发布时间】:2015-07-06 19:20:07
【问题描述】:

我的 html 页面中有一个复选框列表。现在,当用户单击复选框并按下 Donwload 按钮时,我应该能够知道在选中状态下单击了所有复选框。

 <tr st-select-mode="multiple" st-select-row="row"
            ng-repeat="row in orders">
 <td>{{ row.orderid }}<td>
 <td><input type="checkbox" name="{{ row.orderid }}"></td>
 </tr>
 <button type="button" class = "btn btn-default" ng-click="download()">Download Order</button>

因此,当我单击“下载订单”按钮时,我需要传递用于检查复选框状态的 orderid 的值。

那么如何做到这一点。我不知道如何继续。

【问题讨论】:

    标签: html angularjs checkbox


    【解决方案1】:

    您应该在复选框中使用 ng-model,例如:

    <input type="checkbox" ng-model="checkboxModel">
    

    选择或取消选择时,值会发生变化,分别为真或假。

    这个值可以通过调用$scope.checkboxModel来访问

    如果您想遍历所有复选框,最有用的方法是将它们添加到数组中。这可以通过使用 ng-init 来完成:

    <td ng-init="yourArray.push(row.orderid)"></td>
    

    如果您将其粘贴到您的 tr(在您的 ng-repeat 中),它会在每次添加订单时执行此操作。然后如果有人点击下载按钮,你可以循环遍历这个数组来查看它是否被选中。 (您仍然需要使用 ng-model 而不是 name)。

    一个更好的解决方案是

    <input type="checkbox" ng-model="checkbox[row.orderid]"></input>
    

    这样,每个复选框都将位于 $scope.checkbox 数组中,您可以使用 for each 循环遍历该数组并获得所有真假结果。有了这个解决方案,您甚至不需要 ng-init!

    【讨论】:

    • 但是如何查找已单击的多个复选框。有什么方法可以添加到数组中
    • 我编辑了我的答案以更准确地解决我认为您遇到的问题
    • 我尝试了您的代码.. 我能够将选中和未选中状态设置为真和假。我成功地将所有 id 推送到数组中。但是如何在控制器中知道哪个 id 已被检查。
    猜你喜欢
    • 1970-01-01
    • 2016-09-21
    • 1970-01-01
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 2019-12-20
    相关资源
    最近更新 更多