[英]Pass the form data in the URL after clicking on the drop down list values using javascript?
我的形式如下:我使用 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>
以下是您可以在表單中執行的操作:
<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
上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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.