douan4347 2019-07-14 17:16
浏览 88
已采纳

如何通过PHP通过“其他”选项传递下拉值?

enter image description hereI want to pass the option value to another page. For this purpose I have some options. Besides there is an "other" option where an input field is hidden. My javascript code works i.e; selection of "others" appear the desired text input. But while passing the value (submitting) the "other" option (input field) pass the value but not the regular option.

function CheckColors(val) {
  var element = document.getElementById('color_change');
  if (val == 'pick a color' || val == 'others')
    element.style.display = 'block';
  else
    element.style.display = 'none';

}
<form action="action_dropdown.php" method="post">
  <select name="color" onchange='CheckColors(this.value);'>
    <option>pick a color</option>
    <option value="red">RED</option>
    <option value="blue">BLUE</option>
    <option value="others">others</option>
  </select>
  <input type="text" name="color" id="color_change" style='display:none;' />
  <input value="calculation" type="submit">
</form>

$myVariable = $_POST["color"];

echo $myVariable;

I expect my output would be red/ blue/ (while selecting any of them). Again I want my output would be yellow (when I choose "ohters" and input "yellow".)

Being a novice I Hope your cordial cooperation.

</div>
  • 写回答

1条回答 默认 最新

  • doufu1970 2019-07-14 17:21
    关注

    You need to rename your input element by any other as below:

    <form action="action_dropdown.php" method="post">
      <select name="color" onchange='CheckColors(this.value);'>
        <option>pick a color</option>
        <option value="red">RED</option>
        <option value="blue">BLUE</option>
        <option value="others">others</option>
      </select>
      <input type="text" name="othercolor" id="color_change" style='display:none;' />
      <input value="calculation" type="submit">
    </form>
    

    And when your form is submitted, you need to check whether othercolor is set or not. Thus you can get color value like below:

    $selectedColor = ($_POST['color'] == "others" ) ?  $_POST['othercolor']: $_POST['color'];
    

    Thus, you will be able to access both select and input values. Hope it helps you!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码