【问题标题】:How to pass the value from input checkbox to URL Parameters in jquery如何将输入复选框中的值传递给jquery中的URL参数
【发布时间】:2021-11-06 00:20:11
【问题描述】:

我正在尝试根据表单选择的输入更新 url 参数。

<form method="get" action="current.php" id="header-form">   
  <input type="hidden" name="location" value="location">
  <input type="checkbox" name="type[]" class="type" value="opt1"> option1
  <input type="checkbox" name="type[]" class="type" value="opt2"> option2
  <input type="checkbox" name="type2[]" class="type1" value="new1"> new1
  <input type="checkbox" name="type2[]" class="type1" value="new2"> new2
</form>

jQuery

通过选中复选框,我想将值附加到 URL

我的 Jquery

<script type="text/javascript">
  $(document).ready(function() {
    $(".type").change(function () {
      $("#header-form").trigger("submit");
    });
    $(".type1").change(function() {
      $("#header-form").trigger("submit");
    });
  });
</script>


如果我选择选项 1,它工作正常,如果我尝试选择选项 2,它会从 URL 中删除选项 1。

如果我选择选项 1 和选项 2

网址应该是 -> http://localhost.current.php?type=option1&option2

如果我选择所有值 option1 & option 2 和 new 1 & new 2

网址应该是 -> http://localhost.current.php?type=option1&option2?type1=new1&new2

如果我选择值 option1 & new 1 & new 2

网址应该是 -> http://localhost.current.php?type=option1?type1=new1&new2

【问题讨论】:

  • 你用 Ajax 发送吗?
  • 不,我不知道如何在 Ajax 中执行此操作。通过ajax发送会很棒。我在页面上有 php 查询来显示基于 url 参数的结果。
  • 那么为什么每次复选框更改时都提交表单? #property 是什么?
  • 我想将值附加到 url。
  • 如果您使用提交按钮,这将通过单击提交按钮来实现。你有理由不这样做吗?

标签: javascript php html jquery


【解决方案1】:

您必须保留之前的提交数据。
用 PHP 做到这一点:

<form method="get" action="current.php" id="header-form">

    <input type="hidden" name="location" value="location">
    <input type="checkbox" name="type[]" <?php if(isset($_GET['type']) && in_array('opt1', $_GET['type'])): ?>checked<?php endif; ?> class="type" value="opt1"> option1
    <input type="checkbox" name="type[]" <?php if(isset($_GET['type']) && in_array('opt2', $_GET['type'])): ?>checked<?php endif; ?> class="type" value="opt2"> option2

    <input type="checkbox" name="type2[]" <?php if(isset($_GET['type2']) && in_array('new1', $_GET['type2'])): ?>checked<?php endif; ?> class="type1" value="new1"> new1
    <input type="checkbox" name="type2[]" <?php if(isset($_GET['type2']) && in_array('new2', $_GET['type2'])): ?>checked<?php endif; ?> class="type1" value="new2"> new2

</form>

【讨论】:

  • 现在它保留从 URL 中选择的值。谢谢
  • 对不起,有问题,url按预期工作,但复选框选择的值不正确,如果我只选择opt2,页面加载后,选择的选项是[op1]而不是opt2.
  • @user2468312 对不起,你是对的。我更新了我的答案。
  • @user2468312 不客气。
猜你喜欢
  • 1970-01-01
  • 2020-04-05
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-29
相关资源
最近更新 更多