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();
});
$(".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:
nameneeds to be unique. This is good form anyway. I named them box# but you should use more appropriate names that describe what they are.dataattribute to group objects. This is the semantic way to do this.inputs should be in aformtag with anid. This helps you use jQuery selectors to get the objects that you want.valueattribute. You can put a value back in if you’d like to. I just would prefer not see the value attribute in there.