如何使用jQuery在按钮单击时获取所有选中复选框的ID


How to get ids of all checked checkbox on button click using jQuery

<html>  
    <input type='checkbox' id='1' name='checkMr[]' value='1' />       
    <input type='checkbox' id='2' name='checkMr[]' value='2' />            
    <input type='checkbox' id='3' name='checkMr[]' value='3' />         
    <input type='checkbox' id='4' name='checkMr[]' value='4' />        
    <a id="savedoctorschedule" style="float: right;" class="clyes clbutton clbtnSave">Save</a>       
</html> 
<script>
$j("#savedoctorschedule").bind("click", function () { 
    $j.ajax({
        url: "schedulemr.php",
        type: "post",
        data: { schmrid: $j("#sel_mr").val(), 
        schedocid: $j("#checkMr[]").val(), 
        schedate: $j("#date1").val(), },
        success:function(response){         
        }
</script>
<?php
include '../includes/include.php';
$schmrid = $_POST['sel_mr'];
$schedate = $_POST['date1'];
$schedocid = $_POST['checkMr'];
foreach($schedocid as $a => $b)
{
   $sql="INSERT INTO tbl_mr_schedule(doctor_idscheduled_date) 
   VALUES ('".$schedocid[$a]."','".$schmrid."','0','".$date."','".$schedate."');";
   mysql_query($sql) or die(mysql_error());
}
header('Location:../visitplan/');
?>

我想要使用 jQuery 选中复选框的所有 ID;复选框可能是n号。我想在数据库中插入选中复选框的值,其中记录数将取决于选中复选框的数量。这将使用 PHP 作为服务器端脚本。

我该如何解决它?

试试下面,

$(':checkbox[name="checkMr[]"]:checked') //returns you the list of selected checkbox

然后你可以,

var selectedID = [];
$(':checkbox[name="checkMr[]"]:checked').each (function () {
    selectedID.push(this.id);
});

演示

$("#savedoctorschedule").click(function(e){
    e.preventDefault();
    var sList = "";
    $('input[name="checkMr[]"]').each(function () {
        if(this.checked){
            sList += "(" + $(this).attr('id') + ")";
        }
    });
    alert(sList);
    }
);​

请找到小提琴

由于多种原因,您的文档无效。跳过明显的(缺少doctype/<body>/etc),id 属性可能不以数字开头; id="1"无效。您必须使用非数字前缀(如 id="check-1")或将 ID 分配为复选框的value

修复此问题后,您可以使用以下命令查找所有选中的复选框,并检索其值(或您选择使用的任何属性)。

$("input:checked").map(function () { return $(this).val(); });

Id 不能以数字开头。更新 id 后,请使用 attr('value') 或 .val() 检索与输入关联的值。