Check if the checkbox is checked or not.

As per my previos post, what I did was get all the categories, now I wanted to change the categories checkbox status using ajax. For this I had to get the category ID and the checkbox status using javascript.

My previous Code

@foreach($categories as $category)
            <input class="checkbox_id" type="checkbox" id="{{$category->category_id}}" value="{{$category->category_id}}"
           {{isset($selectedCategories) ? (in_array($cateogry->category_id, array_values($selectedCategories->categories->pluck('fk_category_id')->toArray())) ? 'checked' : '') : ''}}>
            <label for="{{$category->category_id}}">
 $('body').delegate('.checkbox_id', 'click', function () {
           var category_id = $(this).data('id');
            if ($(this).is(':checked')) {
                var check_status = 1;
            else {
                var check_status = 0;
            var data = { 'id': category_id, 'check_status': check_status };

function updateCategorty(data) {
                url: '{!! route('updateCategory') !!}',
                type: 'POST',
                data: data,
                success: function (data, textStatus, jqXHR) {
                    if (data.status == 200) {
                    else {
                error: function (jqXHR, textStatus, errorThrown) {
                    toastr.warning("Server error. Please try again later");

What we are doing here is checking if the input class with ‘checkbox_id’ is changed or not. If it is changed, then the next if statement will check if it is checked, and if its true then the ‘check_status’ variable will get the value to be 1 else the value will be 0.

All of the variables are assiged to the variable ‘data’. Then I have called the function updateCategory(data) where all the ajax call is done. The data is routed to the give route where the controller does the rest of the job.

I hope this helps.

2 thoughts on “Check if the checkbox is checked or not.”

  1. Excellent website. Plenty of helpful information here.
    I am sending it to several buddies ans additionally sharing in delicious.
    And certainly, thank you in your sweat!

  2. I have recently started a site, the info you offer on this site has helped me tremendously. Thanks for all of your time & work. “Men must be taught as if you taught them not, And things unknown proposed as things forgot.” by Alexander Pope.

Leave a Comment

Your email address will not be published. Required fields are marked *