根据单击的 <a> 更改 select 选项

Change select option based on <a> clicked

我以前看过它,但基本上我想做的是当用户点击一个选项 "Missionary Farewell/Homecoming" 时,它会将他们重定向到一个带有下拉菜单的联系表单,其中 "Missionary Farewell/Homecoming" 已在联系表中为他们 select 编辑,并针对各种不同的 <a> 标签和不同的 select 选项执行此操作。

HTML 我要重定向到的表单

<form class="contactform" method="post" action="php/events.php">
  <input class="leftbox halfbox" name="contactname" placeholder="Contact's Name">
  <input class="rightbox halfbox" name="eventname" placeholder="Event Name">
  <input class="leftbox halfbox" name="contactphone" placeholder="Contact Phone">
  <input class="rightbox halfbox" name="contactemail" placeholder="Contact Email">
  <select class="fullbox stubborn" name="eventtype">
    <option>What type of event is it?</option>
    <option value="missionary">Missionary Farewell/Homecoming</option>
    <option value="highlight">Athletic/Dance Featurette</option>
    <option value="birthday">Birthday</option>
    <option value="funeral">Funeral</option>
    <option value="graduation">Graduation</option>
    <option value="anniversary">Anniversary</option>
    <option value="engagement">Engagement</option>
    <option value="other">Other</option>
  </select>
  <textarea class="fullbox" id="textarea" name="otheroption" placeholder="If other, please specify"></textarea>
  <input class="leftbox halfbox" name="eventloc" placeholder="Event Location">
  <input class="rightbox halfbox" name="eventtime" placeholder="Event Duration">
  <textarea class="fullbox" id="textarea" name="otherquestions" placeholder="Do you have any other questions/specifications?"></textarea>
  <input class="fullbox stubborn" id="submit" name="submit" type="submit" value="Submit">
</form>

将锚点的 href 设置为 URL,带有携带事件类型的查询字符串:

<a href="form-page.php?eventtype=missionary">...</a>

在表单页面 form-page.php 上,一个 Javascript 读取 URL,解析 eventtype 参数的查询字符串并相应地设置选项菜单。

为了做到这一点,最好给事件下拉列表一个 id,让我们使用 eventtype:

<select class="fullbox stubborn" name="eventtype" id="eventtype">

然后在结束标记 </body> 之前的 body 末尾,你可以这样写:

<script>
    function getParameterByName(name)
    {
        var url = window.location.href;
        name = name.replace(/[\[\]]/g, "\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }

    ​document.getElementById('eventtype').value = getParameterByName('eventtype');​​​​​​​​​​
</script>

此方法是纯客户端(纯 html),没有 php 或任何服务器端代码来管理页面。

(当然,无需 Javascript 服务器端使用预选选项构建表单页面也可以实现相同的目标)

学分:

函数getParameterByName()来自:How can I get query string values in JavaScript?

这里描述了如何使用 JavaScript 按值更改所选选项: HTML SELECT - Change selected option by VALUE using JavaScript