2011-07-27 13 views
0

我想用類名來驗證所有輸入我使用下面的代碼如何使用jQuery不希望使用任何插件,像驗證

$('#submitbutton').click(function() { 

      $('input.inputme[type=hidden]').each(function() { 

       if($(this).val()==''){ 
        choclates='false'; 
       }else{ 
         choclates='true'; 
        }      
      }); 
     if(choclates=='true'){ 
        $('#choclateform').submit(); 
       }else{ 
       alert("Please Fill all Boxes."); 
       } 

     }); 

當我張貼了這個問題來驗證類名的所有輸入代碼是不同的,並沒有充分工作,但這個工程,但我認爲我讓它變得複雜,有人可以做得更好?

回答

1

如果你的目標是防止表單被提交,我會勾窗體上的submit事件,而是和來自處理返回false當發現空白字段(防止被提交的表格)。

// Hook the submit event 
$('#theForm').submit(function() { 
    // Assume all will be fine 
    var valid = true; 

    // Check your inputs 
    $('input.inputme[type=text]').each(function() { 

     // Is this input's value (effectively) blank? Note that 
     // there's no reason whatsoever to use $(this).val(), 
     // with text fields this.value gives you the same thing 
     // more efficiently. 
     // I'm also trimming off whitespace and using the fact 
     // that empty strings are "falsey". 
     if (!$.trim(this.value)) { 
      // Bug user 
      alert("Please fill all boxes"); 

      // Flag that there was a problem 
      valid = false; 

      // Optionally, stop the `each` loop. If 
      // you're *literally* going to use `alert`, 
      // then I'd stop the loop or you'll irritate 
      // people. But if you're showing some kind 
      // of indicator next to the field instead, 
      // then I'd leave this off and continue to do 
      // all fields. 
      return false; 
     } 
    }); 

    if (!valid) { 
     // Cancel submission 
     return false; 
    } 
}); 
+0

@ T-J-克羅德非常感謝您使用註釋我很感激的答案,我剛剛更新了我的問題可以請你在上面或交的新的答案評論? – Yasir

+0

@Yasir:當人們已經回答了原來的問題時,你不應該完全改變這樣的問題。相反,發佈一個單獨的問題。 –

+0

警報需要移動if(!有效語句 – Yasir

-1

試一下這個

$('#formId').submit(function() { 

    $('input.inputme[type=text]').each(function (e) { 

     if($(this).val()=='') { 
      alert("Please fill all boxes"); 

      return false; 
     } 
    }); 

}); 
0

這可以通過白色空格拋出!不是嗎?檢查這個太:

$('#submitbutton').click(function() { 
    var flag = true; 
    $('input.inputme[type=text]').each(function() { 
     if(jQuery.trim($(this).val()) == ''){ 
      alert("Please fill all boxes"); 
      flag = false; 
     } 
    }); 
    return flag; 
}); 
相關問題