简体   繁体   中英

Preselect checkboxes before form submit or first time load?

In a particular form I have a div with 5 checkboxes and I like to preselected all 5 on first load (or when the form has not been submitted).

I thought this was ok, but when I uncheck 2 boxes and I submit the form which reload the same page, all 5 boxes are checked again. And not just the selected ones. I am using a simple PHP ternary to check which div-view box is selected and this works if I remove the following .js

    $(document).ready(function () {
    //Preselect All Div Views
     $("#div-views input:checkbox").prop("checked", true);

    ...
    });

I need to trigger the .js just once, I guess. I am using jquery for most of the javascript handling.

Just remove your javascript code if your form hasn't been submitted yet.

Php

<?php
// If the button is in the $_POST var (or $_GET), the form has already been sent.
if (!isset($_POST['MyButtonName'])) {
?>     
    $(document).ready(function () {
    //Preselect All Div Views
    $("#div-views input:checkbox").prop("checked", true);
<?php } ?>

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