根据{{​​3}} <p> <a> clicked

时间:2016-10-06 02:53:22

标签: javascript html anchor

I've seen it done before, but basically what I'm trying to do is when a user clicks on an option "Missionary Farewell/Homecoming", it redirects them to a contact form with a dropdown menu where "Missionary Farewell/Homecoming" is already selected for them in the contact form, and do that for the various different <a> tags and different select options.

HTML Form I'm redirecting to

<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>

1 个答案:

答案 0 :(得分:1)

将锚点的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