Table of Contents
回复讨论(解决方案)
Home Backend Development PHP Tutorial 怎样才能获取checkbox选择的值?

怎样才能获取checkbox选择的值?

Jun 20, 2016 pm 12:44 PM
How can I get the value selected by the checkbox?


 
这是前台页面,其中“所在部门”和“副职姓名”是jquery从另一个页面get的数据,返回的就是下面的checkbox。我试了一下,从这个页面用js好像找不到这些checkbox,所以只有用php来做了,但是做不出来,下面是部分代码:user是checkbox的name。  
 
$user=$_POST['user'];  
$arr=array();  
$darr=array();  
$darr=  array_diff($arr,$user);  
            if(!empty($user)){  
                 for($i=0;$i if($user=="checked")
//echo "<script>alert('dfh')</script>";  
                $db->query("update members set fuchu='".$_POST['fuchu']."' where uid='".$user[$i]."'");  
                }   
            }  
             
            if(!empty($darr)){  
                for($j=0;$j<=count($darr);$j++){
$rowf=$db->get_one("select * from members where fuchu=".$_POST['fuchu']);  
                    if($darr[$j]==$rowf['uid'])  
                        unset($darr[$j]);  
                    else  
                        $db->query("update members set fuchu='0' where uid='".$darr[$j]."'");  
                }  
            }  
 
我是用的array_diff方法,将选中的和没选中的checkbox区分开来。但是我试了好多遍,主要问题是$_POST['user']返回的是点击的数据,无论是否选中,这样的话如果原来是选中的,我想取消选中的话就做不到,如何能挑出取消选中的数据?

回复讨论(解决方案)

请贴出 html 代码,以甄别数据是以何种方式提交的  
 
或者你 print_r($_POST); 贴出结果


请贴出 html 代码,以甄别数据是以何种方式提交的  
 
或者你 print_r($_POST); 贴出结果


 
 
print_r($_POST); 显示的结果是两个select的值,没什么用。  
Array ( [depart] => 2 [fuchu] => 112 [submit] => 提交 )  
 
这是获取checkbox的jquery代码  
 //city onchange  
            $('#fuchu').change(function() {     
              var city = $(this).val();  
              var province=$("#depart").val();  
              $.get("getdepart.php", {category:'user', city:city,province:province}, function(data) {     
                $('#result').html(data);     
                //alert (data);  
              });     
            });   
 
这是html代码  
if($_REQUEST["city"]!=""){  
            $sql="select * from members left join userclass on members.flag=userclass.flagid where admitright=4 and groupid=".$_REQUEST['province'];  
            $result=$db->query($sql);  
            $str="";  
            if ($db->num_rows($result) > 0) {  
                while ($row =$db->fetch_array($result)) {  
                    if($row['fuchu']==$_REQUEST['city']){  
                        $str.= $row['username'];  
                        $str.= " ";  
                    }else{  
                        $str.= $row['username'];  
                        $str.= " ";  
                    }  
                      
                      
                }  
              }  
                
              mysql_free_result($result);   
        }

提交的数据 Array ( [depart] => 2 [fuchu] => 112 [submit] => 提交 ) 中并没有 user 项  
没有被提交,那自然也就无法处理  
 
#2 下半部只是 php 生成复选框串的代码,并不表示复选框就一定放进表单里去了


提交的数据 Array ( [depart] => 2 [fuchu] => 112 [submit] => 提交 ) 中并没有 user 项  
没有被提交,那自然也就无法处理  
 
#2 下半部只是 php 生成复选框串的代码,并不表示复选框就一定放进表单里去了


 
那为什么print_r($user)和print_r($darr)有数据?


提交的数据 Array ( [depart] => 2 [fuchu] => 112 [submit] => 提交 ) 中并没有 user 项  
没有被提交,那自然也就无法处理  
 
#2 下半部只是 php 生成复选框串的代码,并不表示复选框就一定放进表单里去了


 
那这样的页面形式用什么办法更合适一些?

你是这样使用提交的数据的:$user=$_POST['user'];  
如果 print_r($_POST); 只显示 Array ( [depart] => 2 [fuchu] => 112 [submit] => 提交 )  
你怎么去用 $user ???


你是这样使用提交的数据的:$user=$_POST['user'];  
如果 print_r($_POST); 只显示 Array ( [depart] => 2 [fuchu] => 112 [submit] => 提交 )  
你怎么去用 $user ???


 
我这段代码是在if(isset($_POST['user'])中的,里面的代码可以运行


你是这样使用提交的数据的:$user=$_POST['user'];  
如果 print_r($_POST); 只显示 Array ( [depart] => 2 [fuchu] => 112 [submit] => 提交 )  
你怎么去用 $user ???


 
知道了,只有选中checkbox之后才有内容:  
Array ( [1] => 117 ) Array ( [depart] => 2 [fuchu] => 112 [user] => Array ( [0] => 124 ) [submit] => 提交 )  


你是这样使用提交的数据的:$user=$_POST['user'];  
如果 print_r($_POST); 只显示 Array ( [depart] => 2 [fuchu] => 112 [submit] => 提交 )  
你怎么去用 $user ???


 
现在的问题是取消选中没反应?

复选框没有选中,是不会提交的  
也就是说,$_POST['user'] 是否有值是要分别处理的


复选框没有选中,是不会提交的  
也就是说,$_POST['user'] 是否有值是要分别处理的


 
但是我用array_diff语句处理后的结果并不是我想要的,不知道哪里出错了,帮忙看看,谢谢了

你是说 $darr=  array_diff($arr,$user); 这个?  
你的 $arr 是一个空数组,不管 $user 数组中有多少元素  
$darr 都是空数组,不知道你要这样做的原因


你是说 $darr=  array_diff($arr,$user); 这个?  
你的 $arr 是一个空数组,不管 $user 数组中有多少元素  
$darr 都是空数组,不知道你要这样做的原因


 
我换了种方式,把checkbox写到前台,不从后台get了,现在又遇到点问题:  
 
$("#btnSubmit").bind("click", function () {  
                var result = new Array();  
                  
                $("[name = user]:checkbox").each(function () {  
                    if ($(this).is(":checked")) {  
                        result.push($(this).attr("value"));  
                    }  
                });  
                  
                $("#hdtxt").val(result.join(","));  
                 var userid=;  
                $("#hdfuchu").val(userid);  
                //alert($("#hdtxt").val());  
                alert(userid);  
                  
            });  
 
一加上红字这段select就没反应了,删除掉就可以,这是为什么?我在上面echo $userid,可以看到是有值的。而如果把$userid换成一个数字就可以运行,咋回事?


你是说 $darr=  array_diff($arr,$user); 这个?  
你的 $arr 是一个空数组,不管 $user 数组中有多少元素  
$darr 都是空数组,不知道你要这样做的原因


 
帮忙看看呗,这个项目的最后一点问题了

换一种方式解决了,但是还是不明白为什么$_GET来的变量无法赋值到jquery中。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1272
29
C# Tutorial
1251
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles