2014-02-11 17 views
0

我見過很多人禁用按鈕的例子,如果文本框是空的,但我還沒有找到任何將禁用按鈕只有某些文本框,日期和選擇字段。我是Jquery的新手,我知道它是僞代碼,但你可以明白。我必須致電哪個Jquery函數才能不斷檢查?如何在if子句中使用or語句來確定是否有任何文本框字段爲空?如何禁用提交按鈕時,文本框,選擇和日期是空的,並在其完成時啓用

HTML

<form id="myform"> 
    Username<br /> 
    <input type="text" id="user_input" name="username" /><br /> 
    Password<br /> 
    <input type="password" id="pass_input" name="password" /><br /> 
    Confirm Password<br /> 
    <input type="password" id="v_pass_input" name="v_password" /><br /> 
    Email<br /> 
    <input type="text" id="email" name="email" /><br /> 
    Birthday<br /> 
    <input type="date" id="bday" name="birthday" /><br /> 
    Sex<br /> 
    <select name="sex" id="sex"> 
    <option>Male</option> 
    <option>female</option> 
    </select> 
    <input type="submit" id="register" value="Register" disabled="disabled" /> 
</form> 

的Javascript

<script type="text/javascript> 
(function() { 
    $('#myform > input').keyup(function() { 

     var empty = false; 
     $('form > input #bday').each(function() { 
      if ($(this).val() == '') { 
       empty = true; 
      } 
     }); 

     if (empty) { 
      $('#register').attr('disabled', 'disabled'); 
     } else { 
      $('#register').removeAttr('disabled'); 
     } 
    }); 
})() 
</script> 

JSFIDDLE

+0

你想檢查哪一個空或不空? – putvande

+0

你看過HTML5表單驗證嗎? http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/ – cimmanon

+0

檢查是否可用瀏覽器http://html5pattern.com/ – loveNoHate

回答

0

你可以使用on('input')和改變你的選擇一點:

$('#myform > input').on('input', function() { 

    var empty = false; 
    // Don't use an ID here 
    $('form > input, form > select').each(function() { 
     if ($(this).val() == '') { 
      empty = true; 
     } 
    }); 

    if (empty) { 
     $('#register').attr('disabled', 'disabled'); 
    } else { 
     $('#register').removeAttr('disabled'); 
    } 
}); 

Fiddle

+0

感謝您的幫助和編輯。 – StoledInk

0

您對生日字段進行檢查,因爲日期輸入,生日字段始終填滿。

因此,請確保您在其他領域的檢查是這樣的:

$('form > input.cant_be_empty').each(function() { 
     if ($(this).val() == '') { 
      empty = true; 
     } 
    }); 

而且cant_be_empty類添加到其不能爲空的所有元素。

http://jsfiddle.net/LM4cf/1/

0

我已經更新了你的小提琴。基本上,我已經在需要的字段上添加了必需的屬性。例如,如果你只需要用戶名添加:

<input type="text" id="user_input" name="username" required="true" /> 

然後JS查找所需的字段,並檢查它們是否爲空:

(function() { 
$('#myform > input').keyup(function() { 
    var empty = false; 
    $('form > input[required="true"]').each(function(i, ele) { 
     if ($(ele).val() == '') { 
      empty = true; 
     } 
    }); 

    if (empty) { 
     $('#register').attr('disabled', 'disable'); 
    } else { 
     $('#register').removeAttr('disabled'); 
    } 
}); 
}()) 

就在旁邊,爲什麼不試試這個jQuery驗證插件Here。 您可以選擇提交表單之前需要哪些字段以及驗證用戶輸入(例如驗證電子郵件地址)。

相關問題