javascript - 将选择值传递给链接 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>
解决方案
使用 JavaScript 执行此操作:
document.getElementsByClassName("button")[0].addEventListener("click", function(event) {
var product = document.getElementById("productSelect").value;
event.target.setAttribute("href", "/buy?product=" + product);
});
这将起作用。
推荐阅读
- mysql - mysql查询间歇性地返回空结果
- java - LinkageError 与 org.jboss.logging
- google-data-studio - 是否可以在 Google Data Studio 中的报告之间共享过滤器?
- r - 循环在 R 中完成时间太长
- python - 如何在 python 脚本中添加目录位置?
- android - 使用带有切换屏幕的 StackNavigator 时出错
- java - Windows 10 上 64 位 dll 的无效内存访问仅使用 java11
- javascript - How do I sort an array based on the attribute of corresponding elements of another array using Javascript?
- php - 无法从 Doctrine PHP 连接到 AWS 上的 MySQL 实例
- jquery - 通过 jQuery 将 div 用作模态对话框的最简单方法