2013-02-24 157 views
1

我在想,是否有一個JavaScript命令(什麼是我尋找的東西的專有名稱?)我可以在一個表單中選擇所有輸入框,而不僅僅是一個?Javascript表單驗證

E.g:

function checkform(id){ 
var theForm = document.getElementById(id); 
if (theForm.surname.value == '') { 
    alert("you didn't type in your surname"); 
    theForm.surname.focus(); 
    return false; 
} 
else if (theForm.surname.value.length == 0) { 
    alert('You\'ve left some of the fields blank'); 
    theForm.surname.focus(); 
    return false; 
} 
return true; 
} 

我有這樣的代碼。其目的是檢查表單中的每個輸入框以查看是否輸入了信息,如果沒有,則在用戶提交表單時會顯示警報。

有沒有一種方法可以改變這段JavaScript,以便檢查每個輸入框而不僅僅是姓氏(如示例所示)。

+0

使用jQuery ..... – 2013-02-24 19:41:04

回答

0

方法getElementsByTagName可以給你所有的輸入,elements屬性將持有窗體中所有控件的NodeList。

var nodeList = theForm.getElementsByTagName('input'); 

var nodeList = theForm.elements; 
+0

很酷,所以他們都做同樣的事情? – Joel 2013-02-24 19:53:27

+0

否。前者只會得到輸入,不會得到,例如'select'元素。 – Quentin 2013-02-24 20:08:32

0

我認爲你需要爲這一個document.getElementsByTagName()方法。你可以像這樣與您當前的功能鏈接這件事:

var inputs = document.getElementsByTagName('input'), // get all input tags in the document 
    i = 0, // set counter to zero 
    l = inputs.length; // get number of inputs you have found 
for (i; i < l; i += 1) { // loop through the inputs you have found 
    checkform(inputs[i].id); // send the id of each input to the `checkform` method 
} 

當然,你可能要重寫你必須使它更有效率的功能,但你可能會放棄這一直接進入你的代碼(checkform外功能),它應該做你想做的。