簡體   English   中英

AJAX:禁用提交按鈕,直到用戶名字段填滿電子郵件

[英]AJAX: Disabling submit button until username field is filled with email

我的登錄頁面有三件事:

  1. 用戶名字段
  2. 密碼字段
  3. 提交按鈕

如果用戶名字段不為空,則此代碼將禁用提交按鈕。

我想禁用“提交”按鈕,直到用戶名字段填滿電子郵件為止。

此外,在用戶名字段中寫入內容並清除它之后,提交按鈕不會禁用自身。 我希望提交按鈕在清除用戶名字段后自行禁用。

$(':input[type="submit"]').prop('disabled', true);
 $('input[type="email"]').keyup(function() {
    if($(this).val() != '<!-- not sure what to put here -->') {
       $(':input[type="submit"]').prop('disabled', false);
    }
 });

一個純粹的js解決方案是:

 document.querySelector("input[type=email]").onkeyup = function(){ let reg = /^([A-Za-z0-9_\\-\\.])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]{2,4})$/; (this.value.length==0 || reg.test(this.value)==false)?document.querySelector("input[type=submit]").setAttribute("disabled","disabled"):document.querySelector("input[type=submit]").removeAttribute("disabled") } 
 <form> <input type="email"> <input type="password"> <input type="submit" disabled> </form> 

每當釋放鍵時,這都會檢查輸入值或輸入模式的長度。 如果長度為零或模式不匹配,則它將Disabled屬性設置為Disabled。 如果不是,它將完全刪除禁用的屬性。

您可以使用RegEx驗證電子郵件。 如果條件為false則必須禁用按鈕,如下所示:

 let button = $(':input[type="submit"]'); button.prop('disabled', true); $('input[type="email"]').keyup(function() { if(validateEmail($(this).val())) { button.prop('disabled', false); } else{ button.prop('disabled', true); } }); function validateEmail(email) { var re = /^(([^<>()\\[\\]\\\\.,;:\\s@"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@"]+)*)|(".+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="email"/> <input type="submit" value="Submit"/> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM