首页 > 解决方案 > 将选择选项传递给“a”标签中的href

问题描述

我目前在尝试将值从选择选项传递到按钮时遇到一些困难。我无法弄清楚下一步是什么。

我想将 select 选项中的值传递到按钮上,并将 a 标签的 href 更改为“community/ value ”。

这是代码的摘录:

<div class="communitycpost">
  <strong>View All Posts By:</strong><br>
  <select id="viewallposts" class="viewallposts" name="viewallposts">
    <?php
    require "includes/dbh.inc.php";
    $sql =  "SELECT DISTINCT(cpost_user) FROM cposts;";
    $res = $conn->query($sql);
    while ($rows = $res->fetch_assoc()) {
      $CUser = $rows['cpost_user'];
    ?>
    <option value="<?php echo $CUser; ?>"><?php echo $CUser; ?></option>
    <?php
    }
    ?>
  </select><br>
  <a id="viewalla" href="community/<?php echo $CUser; ?>">
    <button id="cpost_btn" class="cpost_btn" type="button"> View </button>
  </a>
</div>

标签: javascriptphp

解决方案


我最终使用它来尝试解决它!我希望它可以帮助有需要的人!

<script>
   function usrselect() {
      var usr = document.getElementById("viewallposts");
      var comm = "community/"
      var displaytext = usr.options[usr.selectedIndex].text;
      var userurl = comm + displaytext
      document.getElementById("viewalla").href = userurl;
      }
</script>

推荐阅读