jeudi 9 novembre 2017

JQUERY - Keeping checkboxes values checked after submit & refresh

I want to figure out how to use JQuery / Javascript to keep the checkboxes that were checked and the values after the form was submitted or page refreshed. I am still new to JQuery, and I tried several codes and lately I am stuck and need anyone's else. I can either get all checkboxes checked or non at all and it won't work.

Here is the input field which is in a php tag where it pops out all the checkboxes. Please note that I did tried adding php code to remember the boxes that were checked but couldn't get it to remember and work correctly. So far, JQuery / Javascript works. Input HTML / PHP code below:

while ($rowes = pg_fetch_object($result)){
    $lookupid = $rowes->id;
    $item = $rowes->item;               

    echo "<div>
            <div>
                <div>
                    <input type='checkbox' class='product_chk".$lookupid."' id='product_chk' name='camavision[]' value=\" Like '".$item."' \"   ' /> 
                </div>
                <div>
                    <p>$item </p>
                </div>
            </div> 
        </div>";    
}

Here is my basic javascript code:

<script>
    $(function(){
        var itemstored = localStorage.input === 'true'? true: false;
        $('input').prop('checked', itemstored);
    });

    $('input').on('change', function() {
        localStorage.input = $(this).is(':checked');
        console.log($(this).is(':checked'));
    });
</script>

Here is my code that I use to try to get the boxes that were selected before the form was submitted but I get nothing. First I tried saving all the information by using the unique class of the input field into storage. Then if page refreshes, it brings the information up again and checked the correct boxes.

<script>
    $(function () {
        var data = localStorage.getItem("storedItem");
        var index =  $(this).attr('class').replace('product_chk','');
        if (data !== null) {
            $("input[class='product_chk'"+index"]").attr("checked", "checked");
        }
    });
    var index =  $(this).attr('class').replace('product_chk','');
    $("input[class='product_chk'"+index"]").click(function(){

        if($(this).is(':checked')){             
            localStorage.setItem("storedItem", $(this).val());
        } else {
            localStorage.removeItem("storedItem");
        }

    });
</script> 

Please help. (Coding is preferred with a bit of explanation.)




Aucun commentaire:

Enregistrer un commentaire