3

I'm trying to set the value of a checkbox, if checked the value is active, but if unchecked the value is disabled.

The next code works for text, the text changes when the checkbox is checked or unchecked, but the value that is posted to the database is null when the checkbox is unchecked.

HTML

<input type="checkbox" name="cat_status" class="inline checkbox" id="checkbox" checked value="active" onclick="cat_check()">
<label id="text" style="display:Active">Active</label>

JS

function cat_check() {

    var checkBox = document.getElementById('checkbox');
    var text = document.getElementById('text');

    if (checkBox.checked == false) {
        text.style.display = "inline";
        document.getElementById('checkbox').value = "active";
    } else {
        text.style.display = "none";
        document.getElementById('checkbox').value = "disable";
    }
}

I expect the value posted to database to be disabled when the checkbox is unchecked, but currently getting a null.


Update:

Added a fixed version including the AJAX call based on the provided feedback of the answers. This is just in case someone fall into the same issue.

If you play with the example on the bottom of serialize() documentation you will see that value is not appended for checkboxs that are uncheked. You will have to do it manually. Maybe this can help you: how can I override jquery's .serialize to include unchecked checkboxes

HTML

<form method="post" class="add_sub_categories">
  <input type="checkbox" name="cat_status" class="inline checkbox" id="checkbox" checked value="active" onclick="cat_check()">
  <label id="text" style="display:Active">Active</label>
  <a class="btn btn-xs btn-info save_main_cat">GO!</a>
</form>

JS

function cat_check() {

    var checkBox = document.getElementById('checkbox');
    var text = document.getElementById('text');

    if (checkBox.checked == true) {
        text.style.display = "inline";
    } else {
        text.style.display = "none";
    }
}

AJAX

$(document).ready(function() {

    $(".save_main_cat").click(function() {

        var data = $('.add_main_categories').serialize();

        /* This code will include the value for the checkbox when unchecked */
        $(".add_main_categories input:checkbox:not(:checked)").each(function(e) {
            data += "&"+this.name+'=disable';
        });

        $.ajax({
            type: 'POST',
            url: "<?= base_url() ?>admin_ajx/categories_ajx/update_main_categories",
            data: data,
            success: function() {                                                            

                $('#addCat').modal('hide');
                $(".add_main_categories")[0].reset();

                dttable.destroy();

                $(document).ready(function() {
                    main_cat(), main_cat_option(), dt_tables();
                });
            }
        });
    });
});
Community
  • 1
  • 1
dmforaname
  • 63
  • 1
  • 10
  • Lot of issues here. 1) Don't name your IDs the same as elements. Usually your `name` and `id` are the same. 2) You already have a variable for `checkBox`. There's no reason to get it again in the `if/else` statement. Use the variable. 3) You're switching your `true/false` values. If `false` (unchecked), the value is now "active". It should be switched. 4) `display:Active` is not a valid style – Rob Scott May 08 '19 at 03:16

2 Answers2

2

If I understood correctly, the problem is on your click handler. When you unchek the checkbox by clicking on it, the checked property will be false when you observe it inside the click handler. And you are doing this:

 if (checkBox.checked == false)
 {
     text.style.display = "inline";
     document.getElementById('checkbox').value = "active";
 }

So, in other words, you are setting the value to active when the checkbox is unchecked, but instead, that setting should be associated to checked state equal to true. I believe you are looking for something like this:

function cat_check()
{
    var checkBox = document.getElementById('checkbox');
    var text = document.getElementById('text');

    if (checkBox.checked === true)
    {
        text.style.display = "inline";
        checkBox.value = "active";
    }
    else
    {
        text.style.display = "none";
        checkBox.value = "disable";
    }
    
    console.log(checkBox.value);
}
.as-console {background-color:black !important; color:lime;}
<input type="checkbox" name="cat_status" class="inline checkbox" id="checkbox" checked value="active" onclick="cat_check()">
<label id="text" style="display:inline">Active</label>

There are other fixs on the code also:

A) The initial display:Active is not a valid CSS configuration in reference to <label id="text" style="display:Active">Active</label>. So I changed it to display:inline.

B) Use the already defined variable checkBox inside the click handler instead of doing multiple calls to document.getElementById('checkbox').

Shidersz
  • 16,846
  • 2
  • 23
  • 48
  • but if i post , data is still null, result is -> INSERT INTO `tb_categories` (`cat_name`, `cat_dateinput`, `cat_userinput`, `cat_stat`) VALUES ('Test again', '2019-05-08 10:46:10', 'diaz', NULL) – dmforaname May 08 '19 at 03:47
  • i used AJAX to post – dmforaname May 08 '19 at 03:53
  • @dmforaname Can you include the code you are using to post the data in your question? Maybe you are not getting the `value` attribute of the checkbox correctly. – Shidersz May 08 '19 at 03:56
  • @dmforaname Ok, now check what is the output of `console.log(data)` just after you do `var data = $('.add_main_categories').serialize();` when the `checkbox` is `checked` and when is `unchecked`. – Shidersz May 08 '19 at 04:17
  • disable -> cat_name=post%20test&username=diaz&csrf_dm_name=12b35181f1a2b7d029b39b690d343972 enable -> cat_name=post%20test&username=diaz&csrf_dm_name=12b35181f1a2b7d029b39b690d343972&cat_status=active – dmforaname May 08 '19 at 04:31
  • I see, if you play with the example on the bottom of [serialize() documentation](https://api.jquery.com/serialize/) you will see that `value` is not appended for checkboxs that are `uncheked`. You will have to do it manually. Maybe this can help you: https://stackoverflow.com/questions/10147149/how-can-i-override-jquerys-serialize-to-include-unchecked-checkboxes – Shidersz May 08 '19 at 04:39
  • thanks for your help, this problem its fix, i already fix my code above.. – dmforaname May 08 '19 at 05:15
  • @dmforaname Glad to know it helped. Just a reminder for next times: do not fix the code of the original question, that way the posted answers will have little sense now, same will happen with the question (now there is no issue). Instead, add an update section with all the corrections. I have done it for you this time. – Shidersz May 08 '19 at 15:23
  • @dmforaname You're welcome, also remember to choice an answer as correct, if some fits your needs. – Shidersz May 09 '19 at 15:15
0

You can set value 1 , as if it is checked then value posts 1 otherwise can checked null or not;

// In view

//On post time you can check if value is 1 then cheked otherwise null

PHP Geek
  • 3,949
  • 1
  • 16
  • 32