2011-07-08 39 views
0

有文本框a,如果填寫了文本框,確保文本框b在填寫提交時填寫,反之亦然,如果填寫框b,請確保a中包含數據。這可以循環檢查許多文本框,如果文本框的行a有數據檢查第二行的文本框也有數據在行a有。行a中的所有文本框都不需要填寫。謝謝。帶有javascript的文本框驗證

回答

2

你的問題有點難以理解;如果你能更好地解釋你真正想要的東西,這會很有幫助。你不需要有任何條件;只需執行以下操作:

<script> 
function checkForm() { 
    if (!isEmpty(document.myForm.checkA.value) 
     && !isEmpty(document.myForm.checkB.value)) 
     return true; 
    else 
     return false; 
} 

function isEmpty(text) { 
    return text.length == 0 || !text.match(/[^\s]/)) 
} 

</script> 

<form name="myForm" onSubmit="return checkForm();"> 
    <input name="textA" type="text" /> 
    <input name="textB" type="text" /> 
    <input type="submit" value="Submit!" /> 
</form> 
+0

magic * isEmpty *方法來自哪裏? – RobG

+0

哎呦......修正了我的想法。 (太多的Qt!) –

+0

好的,但每次有人這樣做,我必須搜索該死的HTML5規範,看看它是否是一個晦澀API的新方法。 :-) – RobG

1

如果使用數組來保存對文本框的引用,這應該很簡單。例如(從我的頭頂,所以這不會是正確的100%),假設你有5跨和3倒:

var col = new Array(5); 
var row = new Array(3); 
col[0] = document.myForm.checkA1; 
col[1] = document.myForm.checkB1; 
// etc 

row[0] = col; 

col = new Array(5); 
col[0] = document.myForm.checkA2; 
col[1] = document.myForm.checkB2; 
// etc 

row[1] = col; 

col = new Array(5); 
col[0] = document.myForm.checkA3; 
col[1] = document.myForm.checkB3; 
// etc 

row[2] = col; 

現在可以循環陣列上的row[0],如果你找到,例如,那row[0][2]有文本,你只需要驗證row[1][2]也有文本。