17Jan/110

Only Allow Numbers In A Text Box With Javascript

If you are using a text box for quantity in your Magento store, users can enter anything they want as a quantity, letters, dots, symbols, etc... With a few lines of Javascript, you can make sure they are only able to enter numbers.Put this snippet of Javascript anywhere on your product view page (I would recommend product/view/addtocart.phtml).

<script language="javascript">

	function numbersonly(myfield, e, dec)
	{
		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
			return false;
	}
</script>

Open the file app/design/frontend/default/{yourtheme}/catalog/product/view/addtocart.phtml. Find the input text box for quantity. Add this to the input tag:

onKeyPress="return numbersonly(this, event, true);"

...so your input text box code should look something like this:

<input type="text" name="qty" id="qty" maxlength="12" size="2" value="<?php //echo $this->getMinimalQty($_product) ?>" title="<?php echo $this->__('Qty') ?>" onKeyPress="return numbersonly(this, event, true);"/>

Now users will only be able to enter numbers into the quantity field!

About John Webber

John is the founder of MagThemes.com and has been working with Magento since version 0.9
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.