Updating Already Checked Checkboxes in PHP

后端 未结 4 1832
夕颜
夕颜 2020-12-22 03:30

let\'s say I have a list of checkboxes that the user selects.

Water<         


        
4条回答
  •  隐瞒了意图╮
    2020-12-22 03:43

    I tried every variant of the in_array conditional out there and could NEVER get this to work (checking off the checkboxes whose values had been previously selected and thus inserted into the database). I tried complex queries with table joins and no luck with that either. I finally gave up and generated a display:hidden div that opened the array (which for some odd reason I had to IMPLODE rather than explode) and listed its items as comma-separated text. Then I tossed in a little jQuery indexOf() magic to determine if the value of each checkbox was part of said array or not. Took me 10 minutes flat to do this with jQuery, very simple.

    Here's some sample code that is live and working fine:

    Please verify category selections with each update.
    $key
    "; } ?>

    CSS sets that div to invisible:

    .keywords { display:none; visibility:hidden; }
    

    and the jQuery portion:

    $(document).ready(function() {  
        $('.categories input').each(function(index,data) {
            var str=$('.keywords').text();
            var catid = $(this).val();
            var chk = str.indexOf(catid);
            if (chk >= 0) {
                $(this).prop('checked', true);
            }
        });
    });
    

    I hope this helps someone else who is stuck wondering why the in_array conditional is failing them. Since this falls in a twilight zone between data and UI regarding data persistence, I think it's a legit route to take. You have one "echo" statement to generate multiple checkboxes (there are around 40 categories in my situation here) and then a simple jQuery .each() to locate what was selected before and render its corresponding boxes as checked.

提交回复
热议问题