简体   繁体   English

在表单提交或第一次加载之前预选复选框?

[英]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).在一个特定的表单中,我有一个带有 5 个复选框的 div,我喜欢在第一次加载时(或当表单尚未提交时)预选所有 5 个。

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.我认为这没问题,但是当我取消选中 2 个框并提交重新加载同一页面的表单时,再次选中了所有 5 个框。 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我正在使用一个简单的 PHP 三元来检查选择了哪个 div-view 框,如果我删除以下 .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.我想我只需要触发 .js 一次。 I am using jquery for most of the javascript handling.我在大部分 javascript 处理中使用 jquery。

Just remove your javascript code if your form hasn't been submitted yet.如果您的表单尚未提交,只需删除您的 javascript 代码。

Php 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 } ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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