javascript - 如何从表单中调用 js 脚本?
问题描述
我正在写一个有趣的网站,我想根据用户通过表单提交的内容打开不同的页面。应该完成这项工作的功能是“hotelSelection”,但它不起作用。
自动完成功能正常工作。
谢谢您的帮助!
hotelSelection = function()
{
var hotelName = document.getElementById("hotelName").value;
switch (hotelName) {
case Mare Hotel:
window.open("liveItMareHotel.html");
break;
case Hotel 2:
window.open("liveItHotel2.html");
break;
case Hotel 3:
window.open("liveitHotel3.html");
break;
case Hotel 4:
window.open("liveItHotel4.html");
break;
case Hotel 5:
window.open("liveItHotel5.html");
break;
default:
window.open("liveItDefaultList.html");
}
}
<form id="autoForm" autocomplete="off">
<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="hotelName" placeholder="Hotel Name">
</div>
<input type="submit" value="Send" onclick="hotelSelection()">
</form>
解决方案
你这样做的方式是一种不好的做法。您应该在 php 文件中进行重定向并从表单中调用它。无论如何,使用javascript以下代码有效。
html:
<form id="autoForm" autocomplete="off">
<div class="autocomplete" style="width:300px;">
<input type="text" name="hotelName" id="hotelName" placeholder="Hotel Name">
</div>
</form>
<button onclick="hotelSelection()">Send</button>
Javascript:
function hotelSelection() {
var hotelName = document.getElementById("hotelName").value;
switch (hotelName) {
case 'Mare Hotel':
window.open("liveItMareHotel.html");
break;
case 'Hotel 2':
window.open("liveItHotel2.html");
break;
case 'Hotel 3':
window.open("liveitHotel3.html");
break;
case 'Hotel 4':
window.open("liveItHotel4.html");
break;
case 'Hotel 5':
window.open("liveItHotel5.html");
break;
default:
window.open("liveItDefaultList.html");
}
}