簡體   English   中英

通過onkeyup事件Jquery進行文本框驗證,而無需使用警報

[英]Text Box validation through onkeyup event Jquery without using alert

我的html頁面中有以下文本框。

到目前為止,我使用的代碼是。

<input type="text" id = "points" onkeyup="Validate()">
function Validate(){


var text_value = document.getElementById("points").value;
alert(text_value);

   if (!text_value.match(/^[56789]$/) && document.getElementById(called_id).value !="")
    {
       document.getElementById("points").value="";
       //  document.getElementById("points").focus(); 
       alert("Please Enter only between 5 and 10 ");
    }

}     

可接受的值為5、6、7、8、9和10。 我發現了基於onkeyup事件的方法,僅接受5、6、7、8和9。我想知道如何在其中包含10。 我也想知道使用jquery進行onkeyup事件驗證。

  1. 如果用戶提供除此以外的任何其他值,則應在文本框的右側給出“該值應在5到10之間”(不是警告)。
  2. 如果第一個輸入的值為1,則應等待下一個按鍵被按下。 接受是否為0或引發與先前情況相同的錯誤消息。

工作Jsfiddle

我寧願沒有正則表達式:

function validate() {
    var num = document.getElementById("points2").value;
    var num = parseInt(num, 10);
    alert(num);
    if (num < 5 || num > 10) {
        document.getElementById("points2").value = "";
        alert("Please Enter only between 5 and 10 ");
    }
}

將您的正則表達式更改為:

/^([5-9]|10)$/

您應該使用onchange事件:

<input type="text" id = "points"  onchange="Validate()">

function Validate(){    
var text_value = document.getElementById("points").value;
alert(text_value);

   if (!text_value.match(/^([5-9]|10)$/) && document.getElementById(called_id).value !="")
    {
       document.getElementById("points").value="";
       //  document.getElementById("points").focus(); 
       alert("Please Enter only between 5 and 10 ");
    }

}  
$('#textbox').keyup(function() {
    var value = $('#textbox').val();
    if(value != ''){
        if(!value.match(/^[5678910]$/))  
            textboxError();
        else{
            var length = value.length;
            if(value.charAt(length-1) == 0 && value.charAt(length-2) != 1)
                textboxError();
        }
    }
};

$('#textbox').change(function() {
    var value = $('#textbox').val();
    if(value != '')
        textboxError();
    }
};

function textboxError(){
    $('#textbox').val(''); 
    $('#textbox').focus(); 
    alert("Please Enter only between 5 and 10 ");
}

我們正在做的是,

  1. 檢查值是否為空(如果為空,則不執行任何操作)
  2. 如果不為空,則檢查值是否與定義的集合匹配
  3. 如果匹配,則我們檢查10。如果最后輸入的字段項是0,則我們要做的是,前一個字段必須是1,所以它產生10。如果不匹配,則拋出錯誤。
  4. 但這是一個問題,用戶可能輸入1並離開該字段而不輸入其他字符。 因此,您可以通過onchange字段擴展它。
  5. Onchange,現在我們檢查計數為1,並且應該與計數10相匹配。這解決了我們的問題。 您不必擔心0,因為我們已經在keyup塊中對其進行了檢查。

我沒有檢查代碼。 因此,如果有任何錯別字或錯誤,您可以將其替換。

正如Zaheer Ahmed所述, /^([5-9]|10)$/也將捕獲10。 對於事件監聽器,您可以使用

$('#textbox')[0].addEventListener('input', function(event) {
  var value = $(event.target).val();  
  // we already have a reference to the element through the event object,
  // crawling the DOM again is expensive.

  if(value != '') textboxError();
});

這會繞過jQuery,jQuery可能會被某些人皺眉,但是'input'事件會立即觸發,並且如果文本是通過其他方法粘貼或輸入的,它也會起作用。

暫無
暫無

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

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