0

I have been looking through my GCSE project at school and I was trying to make the project look better by making a particular section of my code only accept numbers.

I have made it so that this section of my code limits the user from entering more than 4 numbers . is there a way to make the code only accept numbers ?

<td>
  <input type="text" name="number" maxlength="4" />
</td>
</tr>
  • full code snippet

<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>
  • Is this a duplicate: http://stackoverflow.com/questions/13952686/how-to-make-html-input-tag-only-accept-numerical-values? Or this one: http://stackoverflow.com/questions/469357/html-text-input-allow-only-numeric-input? If not, why not; what makes your question 'new' and unanswered by those previous questions, and their answers? Incidentally, if you want to make it 'better,' you may want to look at the [` – David Thomas Mar 23 '15 at 12:42

3 Answers3

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

If you don't need min and max, just erase it.

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

Use javascript to handle keypress event on that input field and process input the way you like.

jQuery based input helper I use:

/* 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

Ivan Gerasimenko
  • 2,381
  • 3
  • 30
  • 46
0

Try this,

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;
   });
});
K Neeraj Lal
  • 6,768
  • 3
  • 24
  • 33