Dr. Atul Tiwari
Dr. Atul Tiwari

Reputation: 1085

How to call ajax by jquery on multiple checkboxes?

I have multiple (number may go as high as 500) checkboxes, as follows

<?php
$duplicate_checked='';
if ($repeat==1)
{
$duplicate_checked=' checked';
} else {
$duplicate_checked='';
}
?>

<input type="checkbox" name="isrepeat-<?php echo $id_no; ?>" id="isrepeat-<?php echo $id_no; ?>" class ="class_isrepeat" value="<?php echo $id_no;?>" <?php echo $duplicate_checked;?> onclick="updateRepeat(this.checked,<?php echo $id_no;?>);"/><label for="isrepeat-<?php echo $id_no; ?>">Is a duplicate Question?</label>

I want to update the value of Repeat column of the particular question number ($id_no, in this e.g.) in mysql database (e.g. named Qbank) on change of checked value of that checkbox.

I am able to successfully get checked value in javascript function updateRepeat(value, ques_no); But I couldn't get a way to call ajax by javascript.

In jquery this can be done something like -

$('#isrepeat-{question no}').change(function() {
    $.post('update_repeat.php', {ques_no: question_number, repeated: checkbox_value_integer},
    function(data){
    $("#result").html(data);
    });
    });

Edit - 1. #isrepeat-{question no} represents id tag of the checkbox depending on question number eg, #isrepeat-1, #isrepeat-2, #isrepeat-3 etc.

But, This would require definite question number in "#isrepeat-{question-no}". I dont know how to construct this jquery in a way that it automatically picks question no and checked property for any particular checkbox clicked.

If I use class, instead of id for checkboxes then, how can i get question number and checkbox checked value for any checkbox in a single function?

Also, although I have a basic Idea what should be in update_repeat.php for ajax call, it would be nice if you could give any way by which this update can be easily done in ajax.

thanks. regards,

Upvotes: 0

Views: 623

Answers (1)

Teguh Syahmar
Teguh Syahmar

Reputation: 136

Firstly, you are correct by utilizing class as selection to trigger the function. You can then continue by calling $(this) within the trigger callback to utilize the document object for each particular checkbox user clicked on.

Then just use .attr to get an input attribute that stores some information.

Which makes the code into

$('.class_isrepeat').change(function() {
   question_number = $(this).val();
   checkbox_value_integer = $(this).prop('checked');
   $.post('update_repeat.php', {ques_no: question_number, repeated: checkbox_value_integer},    function(data){
       $("#result").html(data);
   });
});

Upvotes: 1

Related Questions