我有一個函數,返回表單中每個文本輸入是否有值。
當我第一次做它看起來像這樣的功能:
function checkInput(inputId) {
check = 0; //should be 0 if all inputs are filled out
for (var i=0; i < arguments.length; i++) { // get all of the arguments (input ids) to check
var iVal = $("#"+arguments[i]).val();
if(iVal !== '' && iVal !== null) {
$("#"+arguments[i]).removeClass('input-error');
}
else {
$("#"+arguments[i]).addClass('input-error');
$("#"+arguments[i]).focus(function(){
$("input").removeClass('input-error');
$("#"+arguments[i]).off('focus');
});
check++;
}
}
if(check > 0) {
return false; // at least one input doesn't have a value
}
else {
return true; // all inputs have values
}
}
這工作得很好,但是當我打電話的功能,我將不得不包括(作爲arstrong textgument)每個輸入我想要的ID待檢查:checkInput('input1','input2','input3')
。
現在我試圖讓我的功能檢查頁面上的每個輸入,而不必包含每個輸入ID。
這是我到目前爲止有:
function checkInput() {
var inputs = $("input");
check = 0;
for (var i=0; i < inputs.size(); i++) {
var iVal = inputs[i].val();
if(iVal !== '' && iVal !== null) {
inputs[i].removeClass('input-error');
}
else {
inputs[i].addClass('input-error');
inputs[i].focus(function(){
$("input").removeClass('input-error');
inputs[i].off('focus');
});
check++;
}
}
if(check > 0) {
return false;
}
else {
return true;
}
}
當我把它返回此錯誤的功能:
Uncaught TypeError: inputs[i].val is not a function
我在做什麼錯?
謝謝。它現在以我想要的方式工作。你是第一個有迴應的人,所以我會給你複選標記。 – krummens
感謝@phprunner,理解這將幫助你很多未來的jQuery代碼。祝你好運。 –