繁体   English   中英

根据<a>点击</a>更改选择选项

[英]Change select option based on <a> clicked

我以前看过它,但是基本上我要做的是,当用户单击选项“ Missionary Farewell / Homecoming”时,它会将他们重定向到带有下拉菜单的联系表,其中“ Missionary Farewell / 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>

将锚点的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()来自: 如何获取JavaScript中的查询字符串值?

此处介绍了如何使用JavaScript通过值更改所选选项HTML SELECT-使用JavaScript通过VALUE更改所选选项

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM