【问题标题】:How to work with checkboxes in jQuery?如何在 jQuery 中使用复选框?
【发布时间】:2013-07-31 19:49:53
【问题描述】:

我对 jQuery 中处理复选框的概念比较陌生。我有三个同名的复选框。现在我只想根据第一个复选框的选择来应用一些条件。供您参考,我的 HTML 代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body> 
<table>
  <tr>
    <td>
      <input type="checkbox" id="users"  value="users"/>Users 
    </td>
    <td>
      <input type="checkbox" id="upload_from_file" value="upload_from_file"/>Upload From File
    </td>
    <td>
      <input type="checkbox" id="copy_paste_from_excel" value="copy_paste_from_excel"/>Copy paste from excel
    </td>
  </tr>
  <tr>
    <td colspan="3">
      <h4>Users</h4>
        <input type="checkbox" class="user_checkbox" name="user_checkbox" id="all_users" value="all_users"/>all users &nbsp;&nbsp;
        <input type="checkbox" class="user_checkbox" name="user_checkbox" id="register_users" value="register_users"/>Register users &nbsp;&nbsp;
        <input type="checkbox" class="user_checkbox" name="user_checkbox" id="package_expired" value="package_expired"/>Package expired &nbsp;&nbsp;
        <input type="checkbox" class="user_checkbox" name="user_checkbox" id="inactive_from_last_month" value="inactive_from_last_month"/>Inactive from last month
    </td>
  </tr> 
</table>
</body>
</html>

我的要求是,当用户选中值为"users" 的复选框时,他/她必须从具有值的复选框组中选择至少一个复选框("register_users""package_expired""inactive_from_last_month")。

还有一个条件是,当用户选择具有值all_users 的复选框时,应禁用同一组中的所有其他复选框,即具有值("register_users""package_expired""inactive_from_last_month")的复选框。

还有一个条件是,当用户选择这些复选框中的任何一个时,应禁用复选框 "all_users"

谁能帮助我使用 jQuery 实现这个功能?提前致谢。如果我在上面的代码中出错了,您可以更正我的代码。我还附上了 UI 的截图。

【问题讨论】:

  • 不要在一个页面(或表单)上多次使用相同的 id 和 name。
  • SO 不是“请为我编写代码”的网站...聘请开发人员或尝试自己学习/做。如果你被困在某个地方,就问一个问题。
  • 这个link的可能重复

标签: javascript jquery html checkbox


【解决方案1】:

如果尚未包含 jQuery 库,您只需将其包含到您的文件中。然后只需编写以下脚本即可实现您想要的功能:

<script type="text/javascript">$("#inactive_from_last_month" ).is(":checked")
$(function(){
  $(".user_checkbox").click(function(){ 
    if($("#all_users" ).is(":checked")) {
      $("#register_users").removeAttr("checked");
      $("#package_expired").removeAttr("checked");
      $("#inactive_from_last_month").removeAttr("checked");
    } else if ($("#register_users" ).is(":checked") || $("#package_expired" ).is(":checked") || $("#inactive_from_last_month" ).is(":checked")) {
      $("#all_users").removeAttr("checked"); }
    });
});
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 2012-11-05
    • 2011-12-22
    • 1970-01-01
    • 2011-01-14
    相关资源
    最近更新 更多