简体   繁体   English

jquery选中复选框选中的值

[英]jquery select check box selected values

<form id="myform">

<input type='checkbox' name='foo[]' value='1'>

<input type='checkbox' name='foo[]' checked='true' value='2' >

<input type='checkbox' name='foo[]' value='3' >

<input type='checkbox' name='foo[]' checked='true' value='4' >

</form>

now using jquery, i need to get selected values of name foo[]. 现在使用jquery,我需要获取名称为foo []的选定值。

Also i need to pass these as an array to a php file ie foo = array(2,4) 另外我需要将这些作为数组传递给php文件,即foo = array(2,4)

Try this 尝试这个

    $("input[type=checkbox]:checked").each(function(){
          arr[]=$(this).val();
   });

to get the values of each element then covert it to json using 获取每个元素的值然后将其转换为json使用

  var myJsonString = JSON.stringify(yourArray);

try this 尝试这个

var val_arr = [];
var arr = $('input[name="foo[]"]:checked');
for(var i=0; i<arr.length;i++){
val_arr.push(arr[i].value);
}
console.log(val_arr);
function submitForm() {
  var form = $('#myform');
  form.submit(function(){ // configure onsubmit event
    form.attr({'method': 'post'}); // set form method to post
    form.attr({'action': 'yourphpfile.php'}); // set file to receive form data
  });
  form.submit(); // submit the form
}

on the php file you can view the contents in $_POST: 在php文件中,您可以在$ _POST中查看内容:

<?php
print_r($_POST);
?>

You can try like this, 你可以这样试试,

var array = new Array();
$('input[name="foo[]"]:checked').each(function(i,el){
        array.push($(el).val());
});
for(var i in array){
   alert("value=="+array[i]);
}

If need you can Read How to check a checkbox is checked using jQuery Post 如果需要,您可以阅读如何使用jQuery Post检查复选框

Try this solution: 尝试此解决方案:

var checkedValues = [];
var checkedElems= $('input[type=checkbox]:checked');

$.each(checkedElems, function(index, element){
   checkedValues.push($(element).val());
});

$.post(
    "something.php",
    {
       arrayOfValues: JSON.stringify(checkedValues),
       ........
    },
    function(data, textStatus, jqXHR){
       alert("Success!");
    }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM