如何制作一个文本框,使其只接受数字

时间:2015-03-23 12:37:37

标签: javascript html

我一直在学校查看我的GCSE项目,我试图通过让我的代码的特定部分只接受数字来使项目看起来更好。

我已经做到这一点,我的代码的这一部分限制用户输入4个以上的数字。有没有办法让代码只接受数字?



<td>
  <input type="text" name="number" maxlength="4" />
</td>
</tr>
&#13;
&#13;
&#13;

  • 完整代码段

&#13;
&#13;
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
 
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="Please enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}

if (document.ExamEntry.subject.value=="") {
msg+="Please enter your subject \n";
document.ExamEntry.name.focus();
document.getElementById('subject').style.color="red";
result = false;
}
 
if (document.ExamEntry.number.value == ""){           
                msg+="Please enter your examination number \n";
                document.ExamEntry.number.focus();
                document.getElementById('number').style.color="red";
                result = false;
        	} else if ( (document.ExamEntry.number.value > 999) & (document.ExamEntry.number.value < 10000)) {
                           var ExamNumber = confirm("Are you sure its the correct examination number ? "+document.ExamEntry.number.value);
                           if(ExamNumber == true) {
                           } else {
                           alert("Oops .  You need to enter your examination number correctly to continue");
                result = false;}
                           } else {
                     msg+=" Oops . You forgot to enter the correct examination number \n";
                result = false;

                     }
                     var checked = null;
var inputs = document.getElementsByName('examtype');
for (var i = 0; i < inputs.length; i++) {
          if (inputs[i].checked) {
           checked = inputs[i];
   }
}
if(checked==null)
{
    msg += "Please select your level of entry \n";
    result = false;
}
else{
    return confirm('You have decided to choose '+checked.value+' as your level of entry for the exam . Is this correct? If so good luck .');
}
                    
        if(msg === ""){
                     return result;
              } else {
                     alert(msg);
                     return result; }
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html" onSubmit="return validateForm();">
<table width="50%" border="0">
	<tr>
	<td id="name">Name</td>
	<td><input type="text" name="name" /></td>
	<tr>
	<td id="subject">Subject</td>
	<td><input type="text" name="subject" /></td>
	</tr>
	<tr>
	<td id="number">Examination Number</td>
	<td><input type="text" name="number" maxlength="4"/></td>
	</tr>
	<tr>
	<p><b>Note:</b> Please don't forget to click on the type of exam that you are sitting.</p>
	<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> GCSE<br />
	<td><input type="radio" id="examtype" name="examtype" value="A-levels" /> A-levels<br />
	<td><input type="radio" id="examtype" name="examtype" value="Betec"/> Betec<br />
	<td><input type="radio" id="examtype" name="examtype" value="Other"/> Other<br />
	</tr>
	<tr>
	<td><input type="submit" name="Submit" value="Submit"     />  </td>
	<td><input type="reset" name="Reset" value="Reset" /></td>
	</tr>
</table>
</form>
</body>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

<form>
  Quantity (between 1 and 5):
  <input type="number" name="quantity" min="1" max="9999">
</form> 

如果您不需要最小值和最大值,请将其删除。

  <input type="number" name="quantity">

答案 1 :(得分:0)

使用javascript处理该输入字段上的按键事件,并按您喜欢的方式处理输入。

我使用的基于jQuery的输入助手:

/* Allows only digits and one point input, restrics length of mantissa */
function DigitsInputHelper(inputSelector, mantissaLength, decimalSeparator) {
    if ($(inputSelector).length > 0) {
        BindKeyPressUpEvents();
        return $(inputSelector);
    } else {
        return [];
    }

    var valueBeforeKeyEnter;

    function BindKeyPressUpEvents() {
        $(inputSelector).keypress(function (e) {
            var code = e.keyCode || e.which;

            if (GetNumberOfDigitsAfterPoint($(this).val()) <= mantissaLength)
                valueBeforeKeyEnter = $(this).val();

            // allowed key codes
            if (code == 8
                || code == 9
                /*|| code == 37 // '%' */ 
                /*|| code == 39 // ''' */)
                return;

            // only digits
            if (mantissaLength == 0 && (code < 48 || code > 57)) {
                e.preventDefault();
            }
            // NOT allowed key codes
            if ((code != 44 || $(this).val().indexOf(decimalSeparator) != -1
                || decimalSeparator != ',')
                && (code != 46 || $(this).val().indexOf(decimalSeparator) != -1
                || decimalSeparator != '.')
                && (code < 48 || code > 57)) {                 // not number
                e.preventDefault();
            }
        });
        $(inputSelector).keyup(function (e) {
            var inputValue = $(this).val();

            if (GetNumberOfDigitsAfterPoint($(this).val()) > mantissaLength)
                $(this).val(valueBeforeKeyEnter);
        });
    }

    function GetNumberOfDigitsAfterPoint(number) {
        var patternDigitsAfterDot = 
            new RegExp("\\" + decimalSeparator +"\\d*");

        if (number.indexOf(decimalSeparator) == -1) {
            return 0;
        } else {
            return patternDigitsAfterDot.exec(number)[0].length - 1;
        }
    }
}

// usage example

DigitsInputHelper("#Total", 2, '.');
DigitsInputHelper("#Total2", 3, ',');
DigitsInputHelper("#TotalNotExist", 2, '.');
DigitsInputHelper("#Total3", 0, '.');

Demo fiddle is here

答案 2 :(得分:0)

试试这个,

HTML

Number : <input type="text" name="number" id="number" />&nbsp;<span id="errmsg"></span>

的Javascript

$(document).ready(function () {
  //called when key is pressed in textbox
  $("#number").keypress(function (e) {
     //if the letter is not digit then display error and don't type anything
     if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        //display error message
        $("#errmsg").html("Digits Only").show().fadeOut("slow");
               return false;

    }
    if($(this).val().length > 3)
       return false;
   });
});