簡體   English   中英

javascript:計算文字輸入中的數字

[英]javascript: counting digits in a text input

我有一段HTML可以創建一個包含三個文本字段(名稱,組和數字)的Web表單,所有這些字段都使用JavaScript進行了驗證,以檢查是否有輸入的數據。 在最后一個文本字段中,我需要引入其他JavaScript來檢查用戶輸入的數據是否也為四位數長(例如2947或94Q3)。 作為一個完全的JavaScript新手,我不確定該怎么做! 我是否必須創建一個可以使用輸入數據的值的變量,然后計算該變量的位數,還是可以直接從現場進行操作? 這是我的代碼的Javascript部分:

function validateForm() {
    var result = true;
    var msg = ””;
    if (document.Entry.name.value == ””) {
        msg += ”You must enter your name\n”;
        document.Entry.name.focus();
        document.getElementById(‘name’).style.color = ”red”;
        result = false;

        if (document.Entry.group.value == ””) {
            msg += ”You must enter the group\n”;
            document.Entry.group.focus();
            document.getElementById(‘group’).style.color = ”red”;
            result = false;
        }

        if (document.Entry.number.value == ””) {
            msg += ”You must enter the number\n”;
            document.Entry.number.focus();
            document.getElementById(‘number’).style.color = ”red”;
            result = false;
        }

        if (msg == ””) {
            return result;
        } {
            alert(msg)
            return result;
        }
    }

如果可能的話,您能告訴我我需要插入什么代碼嗎? 謝謝!

將此塊放置在您的條件列表中:

 if (document.Entry.number.length!=4) {
  msg+=”You must enter 4 digits \n”;
 document.Entry.number.focus();
 document.getElementById(‘number’).style.color=”red”;
 result = false;
}
 if (document.Entry.number.value==””) {
     msg+=”You must enter the number \n”;
     document.Entry.number.focus();
     document.getElementById(‘number’).style.color=”red”;
     result = false;
 }

更改為

if (document.Entry.number.length != 4){
     msg+="Number must be exactly 4 characters \n";
     document.Entry.number.focus();
     document.getElementById('number').style.color="red";
     result = false;
}

暫無
暫無

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

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