![](/img/trans.png)
[英]Passing values of <form> radio buttons to another page for manipulation
[英]Radio buttons in form do not transfer to another web page
在處理我的單選按鈕時,我看不出為什么我的代碼沒有將我帶到指定的網頁:
<form name="login" onsubmit="return validateForm()" method="post">
.
.
<input type="radio" name="ans1" id="yes">Yes<br>
<input type="radio" name="ans2" id="no">No<br>
<input type="submit" value="Login" onclick= "where_to_go();">
</form>
where_to_go()
的腳本:
function where_to_go(){
if (document.login.getElementById('yes').checked) {
// Yes is chosen
document.location.href = "Admin_index.html";
} else if (document.login.getElementById('no').checked) {
// No is chosen
document.location.href ="Log-In_Greet.php";
}
}
有人可以告訴我 go 哪里錯了嗎?
你有兩個問題。
如果您查看了瀏覽器的開發者工具控制台(並啟用了日志保存,因此當您導航到新頁面時它不會被擦除),第一個將會顯示出來。
getElementById
是document
object 和僅document
object 的屬性。 它不是document.logic
的屬性,因此嘗試調用document.login.getElementById
將引發異常。
第二:提交表單時,您正在運行 JS。
JS 運行,告訴瀏覽器導航到兩個頁面之一(或者如果上述問題不存在),然后表單提交繼續並告訴瀏覽器導航到表單的action
URL (您沒有指定“當前 URL”也是如此)。 這將覆蓋 JS 中設置的 URL。
快速而骯臟的解決方案是從onclick
function return false
以便取消提交按鈕的正常行為。
稍微不那么臟的方法是使用type="button"
這樣您就不會首先觸發表單提交。
穩健的方法是編寫服務器端代碼,在 POST 請求上測試使用哪個提交按鈕並發出 HTTP 重定向。 當 JS不可避免地失敗時,這將起作用。
最干凈、最簡單、最可靠的方法是用簡單的鏈接替換單選按鈕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.