我以前见过这样做,但基本上我想做的是,当用户单击“传教士告别/返校”选项时,它会将他们重定向到带有下拉菜单的联系表单,其中“传教士告别”/Homecoming”已在联系表单中为他们选择,并为各种不同的 <a>
执行此操作标签和不同的选择选项。
我重定向到的 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>
最佳答案
将 anchor 的 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
关于javascript - 根据单击的 <a> 更改选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39886766/