[英]Redirect page depending on form submission in Jquery/Javascript?
I'm working on a page that should redirect depending on what the user enters in the form, and I can't seem to figure it out. 我正在开发一个页面,该页面应根据用户在表单中输入的内容进行重定向,但似乎无法弄清楚。 New to Javascript, and eager to learn!
Java语言新手,渴望学习!
Here is the html: 这是html:
<body>
<div id="header">
<div id="navcontainer">
<ul>
<li> <a href="#item1">Home</a> </li>
<li> <a href="#item2">Scents</a> </li>
<li> <a href="#item3">About</a> </li>
<li> <a href="#item4">Contact</a> </li>
</ul>
</div>
</div>
<div id="content">
<p>Hi, how are you feeling today?</p>
<form> <input id="feels" type="text" name="feeling" size="35" onchange="checkfeels(#feels.value);">
<input type="submit" value="submit" >
</form>
</div>
And the Javascript I have so far: 到目前为止,我拥有的Javascript:
function checkfeels(myFeels) {
switch (myFeels)
{
case "good":
document.location.href = 'scents.html';
break
case "bad":
alert(2);
document.location.href = 'scents2.html';
default:
alert("whatever");
}
}
Any help is really appreciated, thanks! 非常感谢您的任何帮助,谢谢!
Put the 放在
return checkfeels(this.elements.feeling.value)
in the form onsubmit attribute. 形式为onsubmit属性。
"feeling" in current case is the name of input field. 当前情况下的“感觉”是输入字段的名称。 <input type="text" name="feeling" > in your code.
在代码中<input type =“ text” name =“ feeling”>。
And add 并添加
return false;
to the end of the checkfeels function to prevent default action (submiting form to server). 到checkfeels函数的末尾,以防止执行默认操作(将表单提交给服务器)。
Also, you can pass to function whole form, for example: 另外,您可以传递完整的函数形式,例如:
return checkfeels(this)
And work already with whole form in checkfeels function. 并已在checkfeels功能中以整体形式工作。
function checkfeels(form) {
var feeling = form.elements.feeling.value;
var otherField = form.elements.otherField.value;
// code with your logic here
return false; // prevent default action
}
Put the following code: 输入以下代码:
checkfeels($('#feels').val());
return false;
in the form onsubmit attribute. 形式为onsubmit属性。
You cannot get what the user types with #feels.value (it seems that you make a mistake between jQuery syntax and javascript). 您无法使用#feels.value来获得用户键入的内容(似乎在jQuery语法和javascript之间犯了一个错误)。
You can do that in pure javascript : 您可以使用纯JavaScript来做到这一点:
function checkfeels() {
var myFeels = document.getElementById('feels').value;
switch (myFeels) {
case "good":
document.location.href = 'scents.html';
break
case "bad":
alert(2);
document.location.href = 'scents2.html';
default:
alert("whatever");
}
}
You get what the user type with : 您将获得用户输入的内容:
document.getElementById('feels').valueand you don't need to give any parameters to the function.
If you use jQuery, you can get the value with : 如果您使用jQuery,则可以使用以下方法获取值:
$('#feels').val();$('#feels')。val();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.