2010-10-26 81 views
0

我想要驗證過程使用Javascript來工作,我的表單有四個單選按鈕和一個提交按鈕,我想這樣做如果用戶單擊提交併且沒有選擇單選按鈕,它會彈出警告並且不會提交表單。下面是我的形式看起來像:使用Javascript驗證表格

<form method="post" name="inform"> 
If you checked off <span style="text-decoration:underline">any</span> problems, how <span style="text-decoration:underline">difficult</span> have these problems made it for you to do your work take care of things at home or get along with other people? 
<table id="lastquestion"> 
<tr> 
<td>Not difficult at all</td> 
<td>Somewhat difficult</td> 
<td>Very difficult</td> 
<td>Extremely Difficult</td> 
</tr><tr> 
<td style="text-align:center"><input type="radio" value="not difficult at all" name="finalquestion" /></td> 
<td style="text-align:center"><input type="radio" value="somewhat difficult" name="finalquestion" /></td> 
<td style="text-align:center"><input type="radio" value="very difficult" name="finalquestion" /></td> 
<td style="text-align:center"><input type="radio" value="extremely difficult" name="finalquestion" /></td> 
</tr> 
</table> 
<input type="hidden" value="<?php echo $totalScore; ?>" name="totalScore" /> 
<input type="submit" value="Submit Final Answer" name="submit" onclick="return validate(inform)" /> 
</form> 

而這裏的腳本是什麼樣子:

function validate(formCheck) 
{ 
    if(formCheck.finalquestion == "") 
    { 
     alert("Please Choose an option"); 
     return false; 
    } 
    else 
    { 
     return true; 
    } 
} 

但由於某些原因,我的按鈕提交不管是什麼,在這裏任何意見將幫助,謝謝!

更新:我試過選擇一個收音機,然後在驗證函數和formCheck.finalquestion報警打印:[對象NodeList],所以我不認爲哪個按鈕被選中的值正確地通過。

+1

不是你的問題的一部分,但我會做,無論你在Javascript多少驗證這樣做,你需要重新做這一切在服務器端的點,因爲它是爲最終很容易用戶可以繞過Javascript驗證。 (你可能已經知道了,但總是值得重申) – Spudley 2010-10-26 15:14:58

+0

謝謝你的建議Spudley :) – 2010-10-26 15:16:35

回答

2

你是依靠命名的行爲只能在IE的作品:只有瀏覽器提供一個全局JavaScript變量xyz(或者,更準確地說,window.xyz)與該name每個元素。

要指定表單,請使用提交按鈕的form屬性。它始終是窗體對象的引用:

return validate(this.form); 

爲了得到一個單選按鈕的元素,你需要指定value屬性。使用

if(formCheck.elements.finalquestion.value == "") 
+0

感謝您的建議Pekka,這在Firefox中工作,但我不得不改變if(formCheck.elements.finalquestion.value ==「」)if(formCheck.elements.finalquestion.value == undefined) – 2010-10-26 15:21:46

+0

@Pete mmmm,或者嘗試'if(!formCheck.elements.finalquestion.value)' - 我認爲如果它可以工作,將會更可取 – 2010-10-26 15:23:04

+0

我明白了,使用您的建議對所有瀏覽器都更友善? – 2010-10-26 15:25:58