我有一个网站,用户可以在其中了解网页或游戏设计,索引上有一个表格,询问他们更喜欢学习哪些内容。我的脚本中唯一有效的部分就是提醒他们,如果他们将表单留空并提交,他们就不会选择。这是代码:
JS:
function validateForm() {
var x=document.forms["form1"]["lesson"].value;
if (x === "web design") {
location.href="web.html";
} else if(x === "game design") {
location.href="game.html";
} else {
alert("You didn't choose. You will remain on the home page.");
}
}
HTML:
<form name="form1" onsubmit="return validateForm()" method="post">
Would you rather learn web design <i>or</i> game design?: <input type="text" name="lesson">
<input type="submit" value="Submit">
</form>
答案 0 :(得分:0)
我建议你继续使用jQuery。它易于使用,减少了代码类型的疲劳。所以,如果您使用jQuery,您的表单将如下所示:
<form id="form1" method="post">
Would you rather learn web design <i>or</i> game design?: <input type="text" id="lesson">
<input type="submit" value="Submit">
</form>
你的jQuery就像:
$(function()
{
$('#form1').on('submit',function()
{
if($('#lesson').trim().val()=="web design")
location.href="web.html";
if($('#lesson').trim().val()=="game design")
location.href="game .html";
else
{
alert("You didn't choose. You will remain on the home page.");
return false;
}
});
});
并且不要忘记将jquery脚本文件包含在html文档的head部分中。转到here获取下载链接。
答案 1 :(得分:0)
[如果我理解您的问题是正确的:]您应该参考form[0]
并设置<form>
的{{1}} - 属性,而不是更改位置。如果没有,为什么还要使用表格呢?我会采用以下非常灵活的方法:
action
并将标记更改为
function validateForm() {
var val=document.forms[0]['lesson'].value;
switch (val) {
case 'web design' :
document.forms[0].action="web.html";
break;
case 'game design' :
document.forms[0].action="game.html";
break;
default :
alert("You didn't choose. You will remain on the home page.");
return false;
break;
}
}
答案 2 :(得分:0)
试试这个
<form name="form1" onsubmit="return validateForm()" method="post">
Would you rather learn web design <i>or</i> game design?:<input type="text" name="lesson" id="lesson">
<input type="submit" value="Submit">
</form>
JS
function validateForm() {
var x = document.getElementById('lesson').value;
if (x === "web design") {
location.href = "web.html";
}
else if (x === "game design") {
location.href = "game.html";
}
else {
alert("You didn't choose. You will remain on the home page.");
}}