使用一个提交按钮在Javascript中输入各种页面

时间:2011-03-05 23:15:19

标签: php javascript html input validating

我想通过按钮进入不同的房间。这在Javascript中是如何实现的。例如,有三个房间,“厨房,卫生间和卧室”。我如何根据自己的选择使用JS进入任何一个房间。所以,如果我在输入框中输入“kitchen”,它会带我去kitchen.php,如果我进入厕所......同样的按钮会把我带到toilet.php等。

这是HTML输入,

<form method="post">
<input style=""name="Text1" type="text"><br>
<input name="move" style="height: 23px" type="submit" value="Move">
</form>

1 个答案:

答案 0 :(得分:1)

只需使用选择字段jsfiddle demo

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 

<head> 
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> 
<title>Untitled 1</title> 
<script type="text/javascript"> 
function submitForm() {
    var myform = document.getElementById('myform');
    var mytext = document.getElementById('room');
    myroom = mytext.value.toLowerCase();
    if (myroom == 'kitchen') {
        myform.action = 'kitchen.php';
        myform.submit();
    } else if (myroom == 'toilet') {
        myform.action = 'toilet.php';
        myform.submit();
    } else if (myroom == 'bedroom') {
        myform.action = 'bedroom.php';
        myform.submit();
    } else return false;
}

window.onload = function(){
     document.getElementById('move').onclick = submitForm;
}
</script> 
</head> 

<body> 
<form id="myform" name="myform" method="post"> 
    <input type="text" id="room" name="room" />
     <button id="move" name="move" style="height: 23px">Move</button> 
</form> 
</body> 
</html> 

在php端创建三个文件来测试这是否有效,toilet.php,kitchen.php和bedroom.php在所有三个文件中都包含以下代码。确保文件名较低:

<?php
echo $_POST['room'];
?>

基本上,根据所选的选项,JavaScript会更改表单的操作URL并提交。如果没有被选中,它将返回false并且不提交。 submitForm函数通过onclick事件附加到move按钮。