本文介绍了如何限制PHP中的复选框选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我已经能够从MYSQL获取数据并使用PHP和HTML将其显示为清单.现在,我想限制一次可以选择的复选框的数量.Javascript似乎不适用于我的PHP代码.

So far I have been able to get data from MYSQL and display it as a checklist using PHP and HTML. Now I would like to limit the number of checkboxes that can be selected at a time. Javascript doesn't seem to be working with my PHP code.

我已经在下面添加了我的JScript,目前无法使用.仅当我将JScript与手动创建的html检查表一起使用时,此JScript才有效,但在下面使用MYSQL数据制作的JScript中,此JScript不起作用.我该如何修复我的Javascript部分,使其正常工作?

I've included my JScript below which is currently not workng. This JScript only works when I use it with manually created html checklists but not the one I have made below using MYSQL data. How can I fix my Javascript part so this works?

这是我的代码:

<?php

    $username = "root";
    $password = "test";
    $hostname = "localhost";

    $dbname = "major_degrees";
    $str='';

    // Create connection
    $conn = new mysqli($hostname, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    $sql = "SELECT degree_name FROM majors";
    $result = $conn->query($sql);

    $out = '';
    $cnt = 0;
    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            $cnt++;
            $out .= '<input id="cb_' .$cnt. '" class="someclass" type="checkbox" />' .$row['degree_name']. '<br/>';

        }
        echo $out;
    } 
    $conn->close();


?>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />

<script>
$out.on("click", ":checkbox", function(event){
        $(":checkbox:not(:checked)", this.form).prop("disabled", function(){
                return $(this.form).find(":checkbox:checked").length == 2;
            });
        });
</script>

推荐答案

尝试一下:

<script>
    $(".someclass").change(function() {
        var count = $(".someclass:checked").length; //get count of checked checkboxes

        if (count > 3) {
            alert("Only 3 options allowed..!");
            $(this).prop('checked', false); // turn this one off
        }
    });
</script>

这篇关于如何限制PHP中的复选框选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 00:19