简体   繁体   中英

Save and Load Checkbox checked states to database

I have a "settings" page in my site and I would like the user to be able to either check or uncheck checkboxes in the settings page. The checkboxes' states should then load when the user logs in.

My idea is to assign ids to each checkbox like this:

 <input type="checkbox" id="chk1" data-col='column1' value="0"/>
 <input type="checkbox" id="chk2" data-col='column2' value="0"/>

and then use jQuery to set the values for each on the checked function like this on the "SAVE SETTINGS" button:

$( "input:checkbox" ).each(function() {
   if $(this).prop('checked'){
    $(this).prop('value','1')
     }
});

and then have a column in my MySql table for each checkbox and then send the value (either 1 or 0) to my database via ajax/php.

Then when the user logs in, I can get the values (1 or 0) for each column and then based on that, I can set the checked state.

Is this a good way to go about it? I want to make sure I don't go down the wrong path if there is a simpler solution or approach.

Assume that $query_array is the container of your db query. Since you've included php in the post's tag you can insert a php tag inside input(assuming the file is a php too):

<input type="checkbox" id="chk1" data-col='column1' value="<?php echo $query[0][col_name];?>"/>

^the 0 above might be an id, and col_name is the column name which contains 0/1

When that is compiled, it should be similar to this:

<input type="checkbox" id="chk1" data-col='column1' value="0"/>

Instead of using jquery why don't you just render the checkboxes with their value already set:

<input type="checkbox" id="chk1" data-col='column1' value="<?php echo $chk1?>" <?php echo $checked?>/>

Edit

If you wanna keep it HTML only you could store the states in a JSON (where the property name is the id of the chekbox and the value it's state) and loop through it as:

$.each(jsonChkbxValues, function(index, val) {
    var elem = $('#' + index);

    elem.prop('value', val);
    if (val) {
        elem.attr('checked', 'checked');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM