【问题标题】:changing form action based on the radio button outside the form根据表单外的单选按钮更改表单操作
【发布时间】:2021-05-27 16:38:44
【问题描述】:

我正在根据数据库中的数据生成表单。所以一组数据基本上是一个带有按钮选择数据的表单。基于另一个单选按钮选择,我想对表单数据做不同的操作。有可能吗?

<form action="">
  <p>Please select user gender:</p>
  <input type="radio" id="male" name="gender" value="male">
  <label for="male">Male</label><br>
  <input type="radio" id="female" name="gender" value="female">
  <label for="female">Female</label><br>
  <input type="radio" id="other" name="gender" value="other">
  <label for="other">Other</label>
</form>

<?php

// here I am generating a list of forms based on some information.
// $fetched_data is the returned array of data (data from db)

// how do I change the form action of the following forms based on the radio buttons above ???

if(!empty($fetched_data))
{
  foreach ($fetched_data as $row)
  {

?>
    <form action = '??????' method =get>
    <tr>
        <td><?php  echo $row["job_options"]; ?>  </td>
        <td><?php  echo $row["salary_options"]; ?>  </td>
        <td><?php  echo $row["place_options"]; ?>  </td>
// buttons
        <td><input type="hidden" name="getID" value=<?php  echo $row["id"]; ?> /></td>
        <td><input type=submit name=serialSubmit value=select id=button1 class = classSubmit /></td>
    </tr>

    </form>
    
<?php
  }
}

?>


【问题讨论】:

  • 您可以使用javascript 解决方案吗?
  • @jpneey 是的。我只是想要一个解决方案;)

标签: php html forms


【解决方案1】:

理想情况下,我将使用选择而不是复选框

<form action="" id="form">
    <p>Please select user gender:</p>
    <select class="gender-select">
        <option value="male">Male</option>
        <option value="female">Female</option>
        <option value="other">Other</option>
    </select>
</form>

然后监听该选择的变化:

<script>
const selectElement = document.querySelector('.gender-select');

selectElement.addEventListener('change', (event) => {
    const selectedGender = event.target.value;
    // then we can change to form's action based on the selected value here
    if (selectedGender == 'male') {
        document.getElementById('form').action = 'http://action/for/male.php';
        return;
    }
    if (selectedGender == 'female') {
        document.getElementById('form').action = 'http://action/for/female.php';
        return;
    }
    // if others
    document.getElementById('form').action = 'http://action/for/others.php';
});
</script>

这个脚本可以极大地优化和压缩,我就这样保留它,这样更容易理解

【讨论】:

    猜你喜欢
    • 2013-07-13
    • 1970-01-01
    • 2017-10-28
    • 2013-11-13
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    相关资源
    最近更新 更多