首页 > 解决方案 > 将选择值传递给链接 URL 参数

问题描述

我有一个Buy按钮,用户可以单击该按钮来购买特定产品。
这会将他们带到我建立的购买表格。
该表单上的一个字段使用 URL 参数,因此它知道用户想要购买哪种产品。

所以我想要做的是在页面的某个位置(Buy按钮所在的位置)有一个 HTML 选择字段,并允许用户在那里选择产品。
然后,当他们单击Buy按钮时,它会通过 URL 传递选定的值。例如:

// Some content here promoting the three products.

// Now I want a select field for the user to choose one of the three products, like this.

<select id="productSelect">
    <option value="product1">Product 1</option>
    <option value="product2">Product 2</option>
    <option value="product3">Product 3</option>
</select>

// Then I have some more content here showing the pros/cons of each product.

// Finally, I have a buy button at the bottom of the page that takes them to the page with the purchase form. 
// Here is where I want to grab the value of the select field and pass it through via the "product" parameter like this.

<a class="button" href="/buy/?product='select value here'">Buy</a>

标签: javascripthtmlstringfunction

解决方案


使用 JavaScript 执行此操作:

document.getElementsByClassName("button")[0].addEventListener("click", function(event) {
    var product = document.getElementById("productSelect").value;
    event.target.setAttribute("href", "/buy?product=" + product);
});

这将起作用。


推荐阅读