【问题标题】:submit form when checkbox change in the same php page当复选框在同一php页面中更改时提交表单
【发布时间】:2016-04-25 22:49:25
【问题描述】:

我有这个代码:

<form id="form" method="post" action="">
<input type="checkbox" name="checkbox" onchange="$('#form').submit();">
<label class="onoffswitch-label" for="myonoffswitch">
    <span class="onoffswitch-inner"></span>
    <span class="onoffswitch-switch"></span>
</label>
</form>


<?php if (isset($_POST['checkbox'])){
echo "ok";} ?>

但复选框的帖子什么都不做

你能帮帮我吗 对不起,我是新手

【问题讨论】:

  • 那么与此相关的 jquery 在哪里?您还标记为 CI。看看你的控制台。
  • ^^ 并且您忘记了操作标签。也许考虑这个页面的 PHP SELF
  • 你的 php 周围没有 php 标签
  • 它不起作用...

标签: javascript php jquery codeigniter checkbox


【解决方案1】:

这是我测试的确切代码,它可以工作。

在显示表单时,它使用isset($_POST['checkbox']) 来决定是否将checked="checked" 添加到HTML 中,因此它会记住用户的选择。然后最后的 PHP 代码根据是否被检查做不同的事情。

<html>
<body>
<script   src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<form id="form" method="post" action="">
<input type="checkbox" name="checkbox" onchange="$('#form').submit();" <?php if(isset($_POST['checkbox'])) { echo 'checked="checked"'; } ?>>
<label class="onoffswitch-label" for="myonoffswitch">
    <span class="onoffswitch-inner"></span>
    <span class="onoffswitch-switch"></span>
</label>
</form>


<?php
     if (isset($_POST['checkbox'])) {
         echo "box is checked";
     } else {
         echo "box is not checked";
     }
?>
</body>
</html>

DEMO

【讨论】:

  • 它有效,谢谢!但如果复选框被选中=“选中”它不起作用
  • 只有选中的复选框才会发送到服务器。因此,如果未选中该框,isset() 将为 false。如果该框最初在 HTML 中被选中,单击它会取消选中它,因此不会在 $_POST['checkbox'] 中发送任何内容。
  • 所以它只在用户选中该框时打印ok,而不是在取消选中它时打印。
  • 我也需要它,当您取消选中该复选框时,程序会执行某些操作...可能吗? @Barmar
  • 我更新了答案以显示它如何记住该框是否被选中,并根据情况显示不同的答案。
【解决方案2】:

很多解决方案,但这里是快速的一个:

<form id="form" method="post" action="">
<input type="checkbox" name="checkbox" onchange="this.form.submit();">
<label class="onoffswitch-label" for="myonoffswitch">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</form>

【讨论】:

  • 我在 chrome & Firefox 中测试过,你可以用 IE 对吗?
  • 复制并粘贴我的代码并再次检查,我在chrome中测试它很好
  • 如果你坚持使用 JQuery,你的代码没问题,只要检查你是否包含正确的 JQuery 库,把它放在头标签之间
猜你喜欢
  • 2023-03-20
  • 2022-01-19
  • 2013-06-24
  • 2013-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多