将选择值传递给链接URL参数

时间:2018-11-05 01:17:48

标签: javascript html string function

我有一个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>

1 个答案:

答案 0 :(得分:1)

使用JavaScript执行此操作

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

这将起作用。