简体   繁体   English

通过单击按钮更改 select 输入的选项

[英]Change option on select input by clicking on a button

I want to change the value on my select input by clicking on a button, but this button is on an other page.我想通过单击一个按钮来更改我的 select 输入的值,但这个按钮在另一个页面上。

My button is on the home page and the form with the select input is on contact page.我的按钮在主页上,输入 select 的表单在联系页面上。 The select input look like this: select 输入如下所示:

<select name="menu-vol" class="wpcf7-form-control wpcf7-select wpcf7-validates-as-required select-field w-select" id="select-vol" aria-required="true" aria-invalid="false">
<option value="">---</option>
<option value="Le marmaille">Le marmaille</option>
<option value="Le Vol découverte">Le Vol découverte</option>
<option value="Le plus">Le plus</option>
<option value="L'infini">L'infini</option>
<option value="Le vol des Hauts">Le vol des Hauts</option>
<option value="Le vol de distance">Le vol de distance</option>
<option value="Le vol du Maïdo">Le vol du Maïdo</option>
</select>

For exemple i want when i click on the button, the input select value change to "Le Vol découverte"例如,当我单击按钮时,我希望输入 select 值更改为“Le Vol découverte”

I'm trying this solution but isn't work because is not a bootstrap template i think and in this exemple the form input and the button is on the same page, not like my case.我正在尝试这个解决方案,但没有用,因为我认为这不是一个引导程序模板,在这个例子中,表单输入和按钮在同一页面上,不像我的情况。

You can achieve this in very simple step:您可以通过非常简单的步骤实现此目的:

In home page make your button an anchor tag like below:在主页中,将您的按钮设为锚标记,如下所示:

<a href="contact.html?param=test">Goto Contact</a>

you can see in href I've passed a param with value.你可以在href中看到我传递了一个有值的参数。

Now in contact.html page, just use this below codes:现在在 contact.html 页面,只需使用下面的代码:

if (window.location.search.includes('param=test')) {
  document.getElementById('select-vol').value = 'Le Vol découverte';
}

Now whenever you click the anchor button in home page it redirects to contact.html page with param=test , and in contact.html page I'm checking condition if param=test then show the selected option which I passed as value in js code.现在,每当您单击主页中的锚按钮时,它都会重定向到带有param=test的 contact.html 页面,并在 contact.html 页面中检查条件,如果 param=test 然后显示我在 js 代码中作为值传递的选定选项.

Well let's assume you have a link like this:好吧,假设您有这样的链接:

<a href="contact.html">Contact Page</a>

You can change the href in order to send query parameters to the target page like this:您可以更改 href 以便将查询参数发送到目标页面,如下所示:

<a href="contact.html?selectedValue=Le marmaille">Contact Page</a>

And finally you can get the query value from URL in the Contact page and change the selected option:最后,您可以在联系页面中从 URL 获取查询值并更改所选选项:

const selectedValue = (new URL(document.location)).searchParams.get("selectedValue");
document.getElementById("select-vol").value = selectedValue;

You can read more here .您可以在此处阅读更多内容。

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

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