如何从选定类的元素发送数据

How to send data from the elements with a class selected

本文关键字:元素 数据      更新时间:2023-09-26

问题示例:

我有 html:

<form action="GET">
  <button onclick="$(this).toggleClass('selected')">2000</button>
  <button onclick="$(this).toggleClass('selected')">2001</button>
  <button onclick="$(this).toggleClass('selected')">2002</button>
  <button onclick="$(this).toggleClass('selected')">2003</button>
  <button onclick="$(this).toggleClass('selected')">2004</button>
  <button onclick="$(this).toggleClass('selected')">2005</button>
  <button onclick="$(this).toggleClass('selected')">2006</button>
  <button onclick="$(this).toggleClass('selected')">2007</button>
  <input type="submit" value="submit" />
</form>

和示例数据库的一部分:

year  |  title  |  ...
2000  |  film1
2000  |  film2
2002  |  film3
2001  |  film4
....  |  .....

我需要根据所选字段搜索数据库记录。

你不能

只用一个类来做到这一点。发送表单时,必须确保发送具有name属性的正确input元素。我要做的是删除内联 JS 并添加到切换类以禁用/启用相应的输入。试试这个:

<form action="submit.php" method="post">
    <button type="button">
        2000
        <input type="hidden" name="options[]" value="2000" disabled>
    </button>
    <button type="button">
        2001
        <input type="hidden" name="options[]" value="2001" disabled>
    </button>
    <button type="button">
        2002
        <input type="hidden" name="options[]" value="2002" disabled>
    </button>
    <button type="button">
        2003
        <input type="hidden" name="options[]" value="2003" disabled>
    </button>
    <input type="submit" value="submit"/>
</form>

<script>
    $('button').click(function () {
        $(this).toggleClass('selected').promise().done(function () {
            if ($(this).hasClass('selected')) {
                $(this).find('input').prop('disabled', false);
            } else {
                $(this).find('input').prop('disabled', true);
            }
        });
    });
</script>

您的submit.php将产生如下结果:

array (size=1)
  'options' => 
    array (size=2)
      0 => string '2000' (length=4)
      1 => string '2002' (length=4)