Multidimensional array of multi checkbox group values jQuery post array AJAX
I have the following code. I want to add/remove check-box values to an array and pass to a JavaScript ajax call. I want to be able to pass all sort array to on array for the ajax call. Each time a checkbox is changed it updates the array, which in turn should update the array that's passed to ajax.
<input class='sort1' type='checkbox' value='' name='sort1' />
<input class='sort1' type='checkbox' value='' name='sort1' />
<input class='sort1' type='checkbox' value='' name='sort1' />
<input class='sort2' type='checkbox' value='' name='sort2' />
<input class='sort2' type='checkbox' value='' name='sort2' />
<input class='sort3' type='checkbox' value='' name='sort3' />
<input class='sort3' type='checkbox' value='' name='sort3' />
<input class='sort3' type='checkbox' value='' name='sort3' />
<input class='sort3' type='checkbox' value='' name='sort3' />
var arr_sort = {}
var arr_sort1 = {};
var arr_sort2 = {};
var arr_sort3 = {};
$(".sort1").delegate("input[type='checkbox']", 'change', function() {
var $this = $(this);
if ($this.prop('checked')) {
arr_sort1[$this.attr('name')] = $this.val();
} else {
delete arr_sort1[$this.attr('name')];
}
ajax_call();
});
$("开发者_StackOverflow社区.sort2").delegate("input[type='checkbox']", 'change', function() {
var $this = $(this);
if ($this.prop('checked')) {
arr_sort2[$this.attr('name')] = $this.val();
} else {
delete arr_sort2[$this.attr('name')];
}
ajax_call();
});
$(".sort3").delegate("input[type='checkbox']", 'change', function() {
var $this = $(this);
if ($this.prop('checked')) {
arr_sort3[$this.attr('name')] = $this.val();
} else {
delete arr_sort3[$this.attr('name')];
}
ajax_call();
});
function ajax_call(){
$.ajax({
type: 'POST',
url: "file.php",
data: { thisaction: thisaction, sort: arr_sort},
success: function(data){
$("#results").html(data);
}
});
}
i could maybe do this, but I want to pass the array to php to handle especially if there are more check-box groups added.
Outcome
array (
"sort1" => array("1","2","3"),
"sort2" => array("this","that"),
"sort3" => array("other","ok")
)
or
array (
"sort1" => array("1","2","3"),
"sort2" => array("this")
"sort3" => array()
)
Answer: http://jsfiddle.net/morrison/XS48K/
Notes:
- Each
name
needs to be unique. This is good form anyway. I named them box# but you should use more appropriate names that describe what they are. - Use
data
attribute to group objects. This is the semantic way to do this. - Your
input
s should be in aform
tag with anid
. This helps you use jQuery selectors to get the objects that you want. - I erased the
value
attribute. You can put a value back in if you'd like to. I just would prefer not see the value attribute in there. - You should store all of them in an object or array. This is so you can manage ALL of the checked states in one place.
精彩评论