Premanshu
Premanshu

Reputation: 626

html textbox limitation on decimal input

I have an html text box where I want to limit the numbers after decimal to 4. After an operation it can be achieved using toFixed() but while the user inputs the text is there any way out.

Please guide me.

Upvotes: 0

Views: 3300

Answers (5)

Muhammad Afzal
Muhammad Afzal

Reputation: 1

     function decimal_only(e) {

         var charCode = (e.which) ? e.which : window.event.keyCode
         if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
             return false;
         }

         if (charCode == 46) { //Now Check The Decimal only allow 1 decimal
             if (e.value.indexOf('.') > -1) {
                 return false;
             }
         }
         return true;
     } 

use this function on textbox event onkeypress.

like

onkeypress="return decimal_only(this)"

this will only allow 1 decimal and integer values to users

Upvotes: 0

user180100
user180100

Reputation:

Here's a sample: http://jsfiddle.net/Regisc/5yber/

This use a regexp to validate the content of the input and make use of this function in order to take carret into account.

Tested under Chrome (dev)

Upvotes: 0

enloz
enloz

Reputation: 5824

Just an idea: jsFiddle live demo

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Round to 4 Decimal Places</title>
    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
    <script type="text/javascript">
        $(function() {
            $('#input').keypress(function(){
                try {
                    val = $(this).val().split('.');
                    if(val[1] > 999) return false;
                }catch(e){}
            })
        });
    </script>
</head>
<body>
    <p>Type a decimal number in the TextBox, limited to 4 decimals</p>
    <input id="input" type="text" />
</body>
</html>

Of course, this works only for ., this could be improved by allow only numbers, and check for , too.

Upvotes: 0

Akshay Khandelwal
Akshay Khandelwal

Reputation: 98

Did you Try a REGEX?

The Regex would look like /^[0-9]+.[0-9]{4}$/ where {4} says that Length after . would be 4

Define REGEX: var regex1=/^[0-9]+.[0-9]{4}$/;var yourtextfromTextBox= textBox.text();yourtextfromTextBox.match(regex1); Try this

Upvotes: 1

Dipen
Dipen

Reputation: 891

You can use onkeyup="yourFunction" function to do so.

Upvotes: 0

Related Questions