如果字段由jQuery清空,则禁用发送按钮

前端之家收集整理的这篇文章主要介绍了如果字段由jQuery清空,则禁用发送按钮前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果有一个或多个输入字段为空,如何禁用发送按钮?

我在伪代码中的尝试

  1. if ( $("input:empty") ) {
  2. $("input:disabled")
  3. }
  4. else
  5. // enable the ask_question -button

我一直在阅读这些文章而没有找到正确的解决方

> Official docs about empty:这就像是不相关的,因为它会查找所有输入字段
> a thread about disabled -feature in jQuery:这似乎是相关的
> to be able to test jQuery Firefox/terminal:获得测试环境对我最有帮助

我现在使用以下代码.
它包含一个关于角色的错误;但是我找不到它.

#1

  1. $(document).ready(function(){
  2. $("#ask_form").validate(){
  3. rules: {
  4. username {
  5. required: true,minlenghth: 2
  6. },email: {
  7. required: true;
  8. minlength: 6
  9. },password {
  10. required: true,minlength: 6
  11. }
  12. }
  13. });
  14. }

#2 Meder的代码

我轻轻地修改了Meder的代码.它会永久禁用send -button,因此它也有bug.

  1. $(document).ready(function(){
  2. var inputs = $('input','#ask_form'),empty = false;
  3. // can also use :input but it will grab textarea/select elements and you need to check for those..
  4.  
  5. inputs.each(function() {
  6. if ( $(this).val() == '' ) {
  7. empty = true;
  8. return;
  9. }
  10. });
  11.  
  12. if ( empty ) {
  13. $('.ask_question').attr('disabled','disabled'); // or true I believe.
  14. }
  15. });

解决方法

  1. var $submit = $("input[type=submit]");
  2. if ( $("input:empty").length > 0 ) {
  3. $submit.attr("disabled","disabled");
  4. } else {
  5. $submit.removeAttr("disabled");
  6. }

猜你在找的jQuery相关文章