2013-01-05 54 views
1

我需要幫助。當我提交這個表單時,我希望它自動重定向到選擇列表中的值選項(這是url)。因此,在按下提交在選擇列表中選擇艾哈邁達巴德需要幫助來重定向提交表格

它應該重定向到http://intranet.guj.nic.in/passport

目前,它沒有進行重定向。 使用內嵌JavaScript代碼的最佳方式是什麼?

<html><body> 
<form id="pass-form" > 
<select id="pass-dropdown" ><option selected="selected">Select Passport Office 
for Status page </option><option value="http://intranet.guj.nic.in/passport/">Ahemadabad 
</option><option value="http://passportstatus.nic.in/passmain.php?city=asr">Amritsar 
</option><option value="http://rpobangalore.gov.in/npassport.asp">Bangalore 
</option><option value="http://passportstatus.nic.in/passmain.php?city=bly">Bareilly 
</option></select> 
<input type="submit" onsubmit="var sel = document.getElementById('pass-dropdown'); window.location = sel.options[sel.selectedIndex].value" /> 
</form> 
</body> 
</html> 
+0

你可能想看看: 的http://計算器.com/questions/138884/when-should-i-use-inline-vs-external-javascript and http://css.dzone.com/news/why-inline-css-and-javascript- – Sam

+0

另外爲什麼不用你只是使用鏈接而不是下拉列表?或者,您可以通過服務器端腳本執行此操作。只需設置標題等於$ _GET ['form']。 – Sam

+0

由於表單已被提交,因此'window.location'不會觸發。您需要防止默認的提交行爲,或者在服務器端處理它。例如'<?php if(isset($ _ POST ['pass-dropdown'])&& $ _POST ['pass-dropdown'])header('Location:'。$ _POST ['pass-dropdown']); exit (); ?>應該做這項工作。 – PassKit

回答

6

這將是更好onsubmit<form>元素的事件,而不是提交按鈕的事件。

更改您的形式代碼:

<form id="pass-form" onsubmit="window.location.href = 'newlocation'; return false;"> 
... 
    <input type="submit" value="Submit" /> 
</form> 
+0

但這種方式不會重定向。 – AgA

+0

它將重定向代碼放在onsubmit並返回false。 – techfoobar

+2

http://jsfiddle.net/Udv7U/ – RichardTowers

1

更改type = "submit"到按鈕

<input type="button" onclick="var sel = document.getElementById('pass-dropdown'); window.location = sel.options[sel.selectedIndex].value" /> 

更新

<input type="button" onclick="var sel = document.getElementById('pass-dropdown'); 
     var frm = document.getElementById("pass-form"); frm.action = sel; frm.submit();" /> 

,如果你把在函數和調用函數,而不是

+0

謝謝,但我想保持type =「submit」是否可以在表單中更改ACTION並以同樣的方式提交它? – AgA

+0

是的。 'frm = document.getElementById(「pass-form」); frm.action = sel; frm.submit();' – codingbiz

0
<form id="pass-form" onsubmit="var sel = document.getElementById('pass-dropdown'); window.location = sel.options[sel.selectedIndex].value" > 
    ... 
    <input type="submit" /> 
</form> 

您必須執行提交屬性的表單標籤。那麼它應該工作。 http://www.w3schools.com/jsref/event_form_onsubmit.asp

+0

它不起作用。 – AgA

+1

使用'window.location.replace(sel.options [sel.selectedIndex] .value)'而不是'window.loaction = ...'http://www.w3schools.com/jsref/met_loc_replace.asp – ijo

1

在某些情況下,你可能需要使用return以確保所需的返回值被使用:

<form onsubmit="return redirectMe();"> 
    <input placeholder="Search" type="text"> 
</form> 

... more code here ... 

function redirectMe() { 
    window.location.replace("http://stackoverflow.com"); 
    return false; 
} 

來源:How to pass an event object to a function in Javascript?