Solved

Limit a form input to numbers only

Posted on 2004-04-23
21
3,344 Views
Last Modified: 2012-08-13
Hi,

I'm looking for an efficient but well written script for error-checking use on my shopping cart page.  On my shopping cart form, where people enter the quantity they want to buy, I need the form to limit their input to numbers only and quantity limited to 99.  For example, if someone enters "4A" I want the quantity to show only 4; another example, if someone enters 68, it will show 68, but if they enter 684 it will drop the first digit entered and only display 84.

The page is written in php, but I think javascript would probably be best for this kind of error checking.

I'm not a programmer, so please keep my install instructions simple.

Thank you for your help.

Steve
0
Comment
Question by:Steve234
  • 5
  • 4
  • 3
  • +5
21 Comments
 
LVL 63

Expert Comment

by:Zvonko
ID: 10897561
Your last example should return 68, not 84.
That mean check lower then 100, if not, then reject last digit.
RoundRobin wraping around only confuses user.


0
 
LVL 63

Expert Comment

by:Zvonko
ID: 10897589
How about this:

<html>
<head>
<script>
function checkQty(theField){
  if(theField.value.match(/\D/)){
    theField.value = theField.value.replace(/\D/g,"");
  };
  if(theField.value>99){
    theField.value = theField.value%100;
  };

}
</script>
</head>
<body>
<form>
<input type=text size="1" onKeyUp="checkQty(this)">
<input type=text size="1" onKeyUp="checkQty(this)">
<input type=text size="1" onKeyUp="checkQty(this)">
</form>
</body>
</html>

0
 

Author Comment

by:Steve234
ID: 10897622
hi,

Then how would they change their input, if they make a mistake?  I thought dropping the digit would be most intuitive?  But I'm open to whatever is usually professionally done.  There are no directions telling the customer there is a limit of 99, I thought they would get the idea if they see what happens to their input if they try to put in more than 99.
Thank you.
Steve
0
 
LVL 31

Assisted Solution

by:GwynforWeb
GwynforWeb earned 50 total points
ID: 10897624
try this the field is edited as they type and when the box looses focus incase they cut and paste

<script>
function edit(val){
 val=val.replace(/[\D]/g,'')
 val=val.replace(/.*(\d{2})$/,'$1')
 return val
}
</script>

<input type=text onkeyup="this.value=edit(this.value)" onblur="this.value=edit(this.value)"'>
0
 
LVL 31

Expert Comment

by:GwynforWeb
ID: 10897631
Zvonko,
     With your try you can cut and paste the value in and the function will not edit it if it is of the wrong form
0
 
LVL 31

Expert Comment

by:GwynforWeb
ID: 10897672
try this it alerts the user (the paste check has gone now and you will have to recheck at form submission)

<script>
function edit(val){
 val=val.replace(/[\D]/g,'')
 if (val.length > 2) alert('please input value less than 100')
 val=val.replace(/.*(\d{2})$/,'$1')
 return val
}
</script>

<input type=text onkeyup="this.value=edit(this.value)">
0
 
LVL 5

Accepted Solution

by:
alambres earned 150 total points
ID: 10897673
<HTML>
<HEAD>
<TITLE></TITLE>
<script type="text/javascript">
      function checkNum(obj)
      {
            var num = parseInt(obj.value);
            if (isNaN(num)) obj.value = '';
            else obj.value = num;
      }
</script>
</HEAD>
<BODY>
<input width="50px" maxlength="2" onblur="checkNum(this);">
</BODY>
</HTML>
0
 
LVL 5

Expert Comment

by:alambres
ID: 10897681
don't need to drop first digit in 684, just limit the digits to allow to 2. just notice: 4a would show 4, but a4 would clear the field.
0
 

Author Comment

by:Steve234
ID: 10897715
Thank you all.

I will have to get feedback from my programmer tomorrow before I award and/or split the points.

Steve
0
 
LVL 5

Expert Comment

by:alambres
ID: 10897743
ok, just another bit of code, if you want a4 not to cleaer the field but show 4 this is:

<HTML>
<HEAD>
<TITLE></TITLE>
<script type="text/javascript">
      function checkNum(obj)
      {
            var num = obj.value;
            var len = num.toString().length;
            for (var i=0;i<len;i++)
            {
                  var a = num.charAt(i);
                  if (isNaN(a))
                  {
                        num = num.replace(a,'');
                        len--;i--;
                  }
            }
            obj.value = num;
      }
      
</script>
</HEAD>
<BODY>
<input width="50px" maxlength="2" onblur="checkNum(this);">
</BODY>
</HTML>
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:Steve234
ID: 10897812
wow, I don't know why my programmer made such a big deal of the custom programming needed to check and limit the quantity input... perhaps he only knows php and not much javascript.  You experts make it seem so easy.
Actually, I don't mind if a4 clears the field, they should not be putting non-numeric characters in the box anyway.
Thank you again.
Steve
0
 
LVL 63

Assisted Solution

by:Zvonko
Zvonko earned 150 total points
ID: 10897835
<html>
<head>
<script>
function checkQty(theField){
  if(theField.value.match(/\D/)){
    theField.value = theField.value.replace(/\D/g,"");
  };
  if(theField.value>99){
    theField.value = theField.value%100;
  };

}
</script>
</head>
<body>
<form>
<input type=text size="1" onKeyUp="checkQty(this)">
<input type=text size="1" onKeyUp="checkQty(this)">
<input type=text size="1" onKeyUp="checkQty(this)">
</form>
</body>
</html>
0
 
LVL 1

Assisted Solution

by:i_rajeevsingh
i_rajeevsingh earned 25 total points
ID: 10897860
Ah i am not regular on this site but
probably this can help

1. This code will not allow any non integer to be entered.(So great help. cause pasting a non integer that too this small is not imaginable)
2. will clear the text if any non integer is pasted
3. too simple to understand
Used it in my commercial application
no probs till date

Rajeev





<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<script language="JavaScript">
function checkPaste(field)
{
if(isNaN(field.value)==true)
field.value=""
}
function allowNumeralOnly(event,field)
{
if ((event.keyCode>=49 && event.keyCode<=57))
{
      if(field.value.length<2)
       return;
      else
       event.keyCode="";
}
else
event.keyCode="";
}
</script>
<body>
    <input type="text" name="text1" onChange="checkPaste(this);" onKeyPress="allowNumeralOnly(event,this);">
</body>
</html>
0
 
LVL 6

Assisted Solution

by:jkna_gunn
jkna_gunn earned 25 total points
ID: 10898142
might as well throw in my solution too!
<script language="JavaScript">
function numbersonly(myfield, e) {

      var key;

      var keychar;



      if (window.event)

         key = window.event.keyCode;

      else if (e)

         key = e.which;

      else

         return true;

      keychar = String.fromCharCode(key);



      // control keys

      if ((key==null) || (key==0) || (key==8) ||

            (key==9) || (key==13) || (key==27) )

         return true;



      // numbers

      else if ((("0123456789").indexOf(keychar) > -1))

         return true;

      

      else if (key == 13 && (myfield.value == ""))

      {

            alert('Please enter a quantity');

            return false;

      }



      else

         return false;

}
</script>
<!-- use like this-->
<input type="text" name="test" onKeyPress="return numbersonly(this,event);">
0
 
LVL 5

Expert Comment

by:alambres
ID: 10898241
you'll doing it complicate. controlling the onblur is enough. The user can paste, drag or whatever he wants, but when exiting  the field, its content is checked, pure and easy.
0
 
LVL 3

Expert Comment

by:azcn2503
ID: 10899186
Indeed, why make it lengthy!?
0
 
LVL 6

Expert Comment

by:Lord_McFly
ID: 10899523
The following example uses a control string which contains valid chars that the user is allowed to enter...

function ValidateKeyStroke(Input)
      {
            var control="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .-@'/";
            var newInput="";

            for(i=0;i<Input.value.length;i++)
                  {
                        chck=Input.value.charAt(i);
                        
                        if(control.indexOf(chck,0)!=-1)
                              {
                                    newInput+=chck;
                              }
                  }
            
            Input.value = newInput;
      }


<input type="text" name="i_0" size="30" maxlength="10" onKeyUp="ValidateKeyStroke(this)">
0
 
LVL 6

Expert Comment

by:jkna_gunn
ID: 10899573
i dont think its lengthy, and i think its a good thing to see the many different ways of achieving the same thing.
0
 

Author Comment

by:Steve234
ID: 10913515
Hi and thank you, everyone.

My programmer used one of the scripts you submitted here.  I'll find out which one he used tomorrow and award points.

Unfortunately, I don't know which one he used yet, but it does work excellent, except it will not allow the number digit of zero to be entered, so the quantities of 10, or 20, or 30 etc cannot be entered.  Otherwise it does work excellent and eliminates a long list of bugs in the shopping cart, beyond entering too big a quantity.

Does the script you submitted prevent the digit zero from being entered?  Let me know.

Thank you.

Steve
www.theBatteryShoppe.com  (under construction)
0
 
LVL 6

Assisted Solution

by:Lord_McFly
Lord_McFly earned 100 total points
ID: 10945988
Do you need any more assistance on this question?

Cheers

McFly
0
 

Author Comment

by:Steve234
ID: 10955012
Hi,

I would like to thank everyone who participated and helped me with the script I needed.  Your assistance is sincerely appreciated.

Thank you.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now