2012-04-24 39 views
0

我想打一個形式在用戶輸入的東西需要被納入鏈接到外部網站的用戶會被重定向到一個文本字段,然後。包含表單數據到URL

讓我們假設用戶輸入'foobar'。點擊提交後,他應該被帶到http://example.com/foobar

這應該最好在JS中,儘管PHP也適用。

到目前爲止,我有這樣的:

<html> 
<head> 
<script type="text/javascript"> 

function genURL() { 
var user = document.getElementById('user'); 
window.location.href = "http://example.com/" + user; 
} 

</script> 
</head> 
<body> 

<form> 
username: <input type="text" name="user"> 
<input type="submit" value="Submit" name="user" onClick="genURL()"> 
</form> 

</body> 
</html> 

這樣做的唯一的事情是添加用戶= foobar的的網址?

我需要做些什麼來完成這項工作?

回答

1

你應該避免的形式被提交。您可以通過將您的函數設爲onsubmit表單的處理程序並返回false來阻止提交表單。

而且你應該在document.getElementById('').value使用.value獲得字段的內容。

的JavaScript:

function genURL() { 
    var user = document.getElementById("user").value; 
    window.location = "http://google.com/" + user; 
}​ 

HTML:

<form onsubmit="genURL(); return false;"> 
    <input type="text" id="user" /> 
    <input type="submit" value="Submit" /> 
</form>​ 

演示:http://jsfiddle.net/jhogervorst/CFHtG/

+0

謝謝,這確實個訣竅! – 2012-04-24 20:19:27

0

您需要用戶元素的值。

var user = document.getElementById('user').value; 
0

請以下嘗試:

function genURL() { 
    var user = document.getElementById('user'); 
    window.location.href = "http://thisisnotarealurl.com/" + user.value; 
} 
0

那豈不是更容易地設置您的形式向您要撥打的URL和表單的方法來獲取行動?

然後你會:

<html> 
    <body> 
     <form action="http://example.com" method="GET"> 
      username: <input type="text" name="user"> 
      <input type="submit" value="Submit" name="user"> 
     </form> 
    </body> 
</html> 

無需JavaScript的:)

0
function genURL() { 
    var user = document.getElementById('user'); 
    window.location.href = document.URL + user.value; 
}