search
HomeBackend DevelopmentPHP 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
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
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft