javascript - 如何限制动态复选框

标签 javascript php jquery mysql

我面临一个复选框问题,一个复选框的动态名称 buy[]。我想给出一个限制。用户只能选择 5 或 6 个复选框。复选框来自数据库表行库。清晰而简单的问题。我已经对其进行了编码,但如果选择复选框 name='bye' ,则需要很少的帮助,那么我的脚本可以工作,但 forEach 不起作用。为我提供有限选择的动态复选框的解决方案。

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <link rel="stylesheet" href="style.css" media="all">

    <script type="text/javascript">

    /***********************************************
    * Limit number of checked checkboxes script- by JavaScript Kit (www.javascriptkit.com)
    * This notice must stay intact for usage
    * Visit JavaScript Kit at http://www.javascriptkit.com/ for this script and  100s more
    ***********************************************/

    function checkboxlimit(checkgroup, limit){
        var checkgroup=checkgroup
        var limit=limit
        for (var i=0; i<checkgroup.length; i++){
            checkgroup[i].onclick=function(){
            var checkedcount=0
            for (var i=0; i<checkgroup.length; i++)
                checkedcount+=(checkgroup[i].checked)? 1 : 0
            if (checkedcount>limit){
                alert("You can only select a maximum of "+limit+" courses")
                this.checked=false
                }

            if (checkedcount>limit){
                alert("You can only select a maximum of "+limit+" courses")
                this.checked=false
                }
            }
        }
    }
    </script>
    <style type="text/css">
    .table tr th {border:1px solid #008080}

    </style>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    </head>

    <body>
    <form action='registration_courses_add.php' autocomplete="off" method='post'  id="world" name="world" >
                                <input type="submit" name="" value="Submit" id="ctl00_MainContainer_btnLoad" class="button-margin SearchKey">

    <h3>Please select course for registration : </h3>
    <p style="color:green">Note: You can select maximum 6 courses </p>

    <table align="center" tabindex="6" cellspacing="0" rules="all" border="1" id="ctl00_MainContainer_gvRegisteredCourse" style="width: 98%;
      border-collapse: collapse;
      margin-left: 17px;">

                <tr style="  color: White;
      background-color: SeaGreen;
      height: 25px;">
                    <th>Course id</th>
                    <th>Course title</th>
                    <th>Course credits</th>
                    <th>Course status</th>
                    <th>Selection</th>


                </tr>

            <?php 
            $db=require "script_database/connect.php"; 

            $query = "
    select 
    c.course_id,c.id,
    c.course_title,
    c.course_credits,
    c.course_status 
    from course c 
    where 
    c.course_id NOT IN (select course_id from completed_course where student_id='1229CSE00241')
    group by c.id 
    ";




            $run=mysql_query($query);
            while($row=mysql_fetch_array($run)){
            $post_id=$row['course_id'];
            $post_date=$row['course_title'];
            $post_author=$row['course_credits'];
            $post_title=$row['course_status'];



            ?>


                <tr align="center" >
                    <td><?php echo $post_id; ?></td>
                    <td><?php echo $post_date; ?></td>
                    <td><?php echo $post_author; ?></td>
                    <td><?php echo $post_title; ?></td>
                    <td><?php print "<input type='checkbox' name='buy[]' value='{$row['id']}' /> "?></td>
                    //if i change buy[] to bye then check box limit work but  foreach{} not work for check box 
                </tr>

                <?php } ?>



                </table>





            </form> 

            <script type="text/javascript">

    //Syntax: checkboxlimit(checkbox_reference, limit)
    checkboxlimit(document.forms.world.buy, 6)
    //here is the problem
    </script>



    </body>

    </html>

最佳答案

这是一个纯javascript方法。这将允许您将该功能用于多个表单/一组复选框

这里我为选择器的元素添加了一个类名,如果您不想使用类名,我已经注释掉了另一种方式

带有类名:

var boxes=document.getElementsByClassName('boxes');

没有类名:

var boxes=document.querySelectorAll("input[type=checkbox]");

我使用了自定义数据属性来设置元素组的复选框的最大数量。这将允许函数根据设置的 data-max 属性和名称以不同的限制运行。

function limit(){
  var count=0;
  //Get all elements with the class name of Boxes
  var boxes=document.getElementsByClassName('boxes');
// ---- Or ------  
//Get all input elements with the type of checkbox.
//var boxes=document.querySelectorAll("input[type=checkbox]");
  //(this) is used to target the element triggering the function.
   for(var i=0; i<boxes.length; i++){
    //If checkbox is checked AND checkbox name is = to (this) checkbox name +1 to count
    if(boxes[i].checked&&boxes[i].name==this.name){count++;}
  }
  //If count is more then data-max="" of that element, uncheck last selected element
  if(count>this.getAttribute("data-max")){
    this.checked=false;
    alert("Maximum of "+this.getAttribute("data-max")+".");
  }
}
//----Stack Overflow Snippet use---\\
window.onload=function(){
var boxes=document.getElementsByClassName('boxes');
// Use if you don't want to add a class name to the elements
//var boxes=document.querySelectorAll("input[type=checkbox]");
  for(var i=0; i<boxes.length; i++){
    boxes[i].addEventListener('change',limit,false);
  }
}
<b>Name:</b> bye[] <b>Limit:</b> 5<br>
<input type="checkbox" class="boxes" data-max="5" name="bye[]"/>
<input type="checkbox" class="boxes" data-max="5" name="bye[]"/>
<input type="checkbox" class="boxes" data-max="5" name="bye[]"/>
<input type="checkbox" class="boxes" data-max="5" name="bye[]"/>
<input type="checkbox" class="boxes" data-max="5" name="bye[]"/>
<input type="checkbox" class="boxes" data-max="5" name="bye[]"/>
<hr/>
  <b>Name:</b> hello[] <b>Limit:</b> 2<br>
<input type="checkbox" class="boxes" data-max="2" name="hello[]"/>
<input type="checkbox" class="boxes" data-max="2" name="hello[]"/>
<input type="checkbox" class="boxes" data-max="2" name="hello[]"/>

如果您不想使用 window.onload 来设置事件监听器,您只需将 onchange 属性添加到复选框元素 onChange="limit(this)" 并更改 function limit(e){ 并将所有 this 替换为 e

如果您有任何疑问,请在下面留言,我会尽快回复您!

我希望这有帮助。快乐编码!

关于javascript - 如何限制动态复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30441866/

相关文章:

javascript - 使用 Three.js 从 DDS 立方体贴图文件加载立方体贴图

php - 函数返回和foreach故障

php - 使用插件向 WordPress 添加新页面

java - 服务器端 - 进度条

javascript - 当您克隆 Backbone.Collection 时,模型引用是否完好无损?

javascript - 客户端缺少 "Access-Control-Allow-Origin" header 的解决方案

php - Ajax 和 PHP - 插入错误

javascript - ajax请求完成,页面刷新后如何保持页面状态

javascript - jquery中鼠标离开和鼠标输入问题并单击到子菜单链接而不是靠近子菜单?

jquery - 更改部分名称属性