【问题标题】:Pass the form data in the URL after clicking on the drop down list values using javascript?使用javascript单击下拉列表值后传递URL中的表单数据?
【发布时间】:2018-03-12 15:48:58
【问题描述】:
我的表格如下:
我正在使用nodejs和javascript。这里根据用户从下拉列表中选择的值,相应地调用该url。就像电影选项一样:“localhost:3000/new”将被调用。这很好用!但它只是在没有任何表单参数的情况下被重定向到 url。我希望表单值也与 url 一起传递。如何做到这一点?
请帮忙?
谢谢:)
<form>
<input type="text" name="currentloc" class="textbox" id="currentloc"
placeholder="Your location"/>
<input type="text" name="destloc" id="destloc" autofocus="autofocus"
class="textbox" placeholder="Enter the destination"/>
First Event : <select name="events" onchange="location = this.value;">
<option value="" >Select your first event</option><br><br>
<option value="/new" name="movies" id="movie" method="get">Watch a
Movie</option>
<option value="/food" name="restuarantis" id="rest" >Restaurant table
booking</option>
</select>
</form>
【问题讨论】:
标签:
javascript
html
node.js
forms
url
【解决方案1】:
您可以在表单中执行以下操作:
<body>
<form name="pickerForm" method="GET" action="">
<input type="text" name="currentloc" class="textbox" id="currentloc" placeholder="Your location" />
<input type="text" name="destloc" id="destloc" autofocus="autofocus" class="textbox" placeholder="Enter the destination" />
First Event :
<select name="events" onchange="return loadCorrectPage(event);">
<option value="" >Select your first event</option><br><br>
<option value="/new" name="movies" id="movie" method="get">Watch a Movie</option>
<option value="/food" name="restuarantis" id="rest" >Restaurant table booking</option>
</select>
</form>
<script>
function loadCorrectPage(event) {
event.preventDefault();
console.log(event.target.value);
document.forms['pickerForm'].action = event.target.value;
document.forms['pickerForm'].submit();
}
</script>
</body>
-
document.forms['pickerForm'] 匹配表单元素 <form name="pickerForm" 因为 name=
- 您必须使用
method="GET" 将表单中的数据发送到您的node.js 后端并在req.query 上提供它们
- 我们使用
action="",因为我们将使用 JavaScript 设置它
- 当您的
select 元素发生更改时,我们会运行函数 loadCorrectPage() 并传入 event 这是一个保存有关 onchange 事件数据的变量
- 然后,我们需要创建函数
-
event.preventDefault() 在这里可能是不必要的,但如果你不这样做,了解它是如何工作的很好
-
event.target.value 保存已更改选项的值
- 我们将
document.forms['pickerForm'].action 更新为更改后的选项,这意味着action="" 现在是action="/new" 或action="/food"
- 我们调用
document.forms['pickerForm'].submit() 提交表单!
现在,在您的 node.js 后端,您需要相应的路由。如果您使用 Express,它们将如下所示:
app.get('/new', function(req, res) {
console.log('\nSomeone just picked movies!');
console.log('Current location:', req.query.currentloc);
console.log('Destination:', req.query.destloc);
});
app.get('/food', function(req, res) {
console.log('\nSomeone just picked restaurants!');
console.log('Current location:', req.query.currentloc);
console.log('Destination:', req.query.destloc);
});