Durga
Durga

Reputation: 565

How allow only numbers and 2 digit decimal in textbox by using jquery

I am new to jquery. I have form with two text boxes. In that i am restrict special characters. But i want allow decimal value.

I implemented decimal code but not working. . is not allowing. And i want to allow 2 digit only after decimal.

<form>
<div class="col-md-6">
<div class="form-group ">
<label for="minAmt" class="col-lg-4 control-label">Min.Amount</label>
<div class="col-lg-6">
<input type="text" class="form-control minAmt" id="minAmt" name="minAmt" placeholder="Enter Min Amount" />
</div>
</div>
<div class="form-group ">
<label for="maxAmt" class="col-lg-4 control-label">Max.Amount</label>
<div class="col-lg-6">
<input type="text" class="form-control maxAmt" id="maxAmt" name="maxAmt" placeholder="Enter Max Amount" />
</div>
</div>
</div>
</form>

Script:

$('#minAmt').keyup(function(){
     if($(this).val() == '0'){
      $(this).val('');  
    }
     if (this.value.match(/[^0-9]/g)) {
         this.value = this.value.replace(/[^0-9]/g, '');
 }
 });
 $('.minAmt').keyup(function (e) {
     var character = String.fromCharCode(e.keyCode)
     var newValue = this.value + character;
     if (isNaN(newValue) || hasDecimalPlace(newValue, 3)) {
         e.preventDefault();
         return false;
     }
 });

 function hasDecimalPlace(value, x) {
     var pointIndex = value.indexOf('.');
     return  pointIndex >= 0 && pointIndex < value.length - x;
 }

What is wrong in my code?

Upvotes: 2

Views: 12243

Answers (4)

trincot
trincot

Reputation: 350097

I would suggest listening to the input event, since modifications can be made with the mouse and/or context menu, that do not generate keyup events.

You could then keep track of the last value that was acceptable and restore that value whenever the input becomes invalid. You can manage that previous value as a data property:

$(function () {
    $('#minAmt,#maxAmt').on('input', function(e) {
        if (/^(\d+(\.\d{0,2})?)?$/.test($(this).val())) {
            // Input is OK. Remember this value
            $(this).data('prevValue', $(this).val());
        } else {
            // Input is not OK. Restore previous value
            $(this).val($(this).data('prevValue') || '');
        }
    }).trigger('input'); // Initialise the `prevValue` data properties
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <div class="col-md-6">
        <div class="form-group ">
            <label for="minAmt" class="col-lg-4 control-label">Min.Amount</label>
            <div class="col-lg-6">
                <input type="text" class="form-control minAmt" id="minAmt" name="minAmt" placeholder="Enter Min Amount" />
            </div>
        </div>
        <div class="form-group ">
            <label for="maxAmt" class="col-lg-4 control-label">Max.Amount</label>
            <div class="col-lg-6">
                <input type="text" class="form-control maxAmt" id="maxAmt" name="maxAmt" placeholder="Enter Max Amount" />
            </div>
        </div>
    </div>
</form>

Upvotes: 1

Akshay Chawla
Akshay Chawla

Reputation: 613

Here is the solution which will allow user to enter only numbers and single period (.).

$('#text').keypress(function (event) {
        return isNumber(event, this)
});

// THE SCRIPT THAT CHECKS IF THE KEY PRESSED IS A NUMERIC OR DECIMAL VALUE.
function isNumber(evt, element) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (            
        (charCode != 46 || $(element).val().indexOf('.') != -1) &&      // “.” CHECK DOT, AND ONLY ONE.
        (charCode < 48 || charCode > 57))
        return false;
        return true;
}

OR

<input id="txtId" type="text"></input>

var txt = document.getElementById('txtId');
txt.addEventListener('keyup', myFunc);

function myFunc(e) {
  var val = this.value;
  var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;
  var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;
  if (re.test(val)) {
    //do something here

  } else {
    val = re1.exec(val);
    if (val) {
      this.value = val[0];
    } else {
      this.value = "";
    }
  }
}

I hope this will fulfill your need.

Upvotes: 2

Ashiquzzaman
Ashiquzzaman

Reputation: 5284

You can try this example:

  $('#minAmt').keyup(function(e) {
    onlyNumeric(e);
    var val= $(this).val();
    if (val=== '') {
        $(this).val('0.00');
    }
  else{
      $(this).val(val.toFixed(2));
   }
    });

function onlyNumeric(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    var exclusions = [8, 46];
    if (exclusions.indexOf(key) > -1) {
        return;
    }
    key = String.fromCharCode(key);
    var regex = /[0-9]|\./;
    if (!regex.test(key)) {
        theEvent.returnValue = false;
        if (theEvent.preventDefault) theEvent.preventDefault();
    }
}

OR

$('#minAmt').keyup(function (e) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    var exclusions = [8, 46];
    if (exclusions.indexOf(key) > -1) { return; }
    key = String.fromCharCode(key);
    var regex = /^\d+(\.\d{0,2})?$/g;
    if (!regex.test(key)) {
        theEvent.returnValue = false;
        if (theEvent.preventDefault) theEvent.preventDefault();
    }
    var val = $(this).val();
    if (!regex.test(val)) {
        $(this).val('0.00');
    }
    else {
        $(this).val(val.toFixed(2));
    }

});

Upvotes: 1

Philipos D.
Philipos D.

Reputation: 2310

Replace:

this.value = this.value.replace(/[^0-9]/g, '');

with

this.value = this.value.replace(/[^0-9_.]/g, '');

Here is a little pen with your code.

Also you could create a jQuery function like this one:

(function($) {
    $.fn.regEx = function(regType) {
        var str = $.trim($(this).val());
        if (regType == "tel") {
            var regx = /^[0-9+./+/-]+$/;
        }

        if (regType == "adr") {
            var regx = /^[A-Za-z0-9+.+,]+$/;
        }

        if (regType == "email") {
            var regx = /^[A-Za-z0-9+@+.+_\-]+$/;
        }

        if (str != "") {

            if (!regx.test(str)) {
                $(this).siblings(".error").css("opacity", "1");
                //alert("Alphanumeric only allowed !");
                $(this).val("");
                setTimeout(function() {
                    $(this).siblings(".error").css("opacity", "0");
                }, 2000);
            } else {
                $(this).siblings(".error").css("opacity", "0");
            }
        } else {
            //empty value -- do something here
        }
    };
})(jQuery);

And use it on your desired elements like this:

$("input#email").keyup(function(e) {
    $(this).regEx("email");
});
$("input#telefon").keyup(function(e) {
    $(this).regEx("tel");
});
$("input#telefon").keyup(function(e) {
    $(this).regEx("adr");
});

And your HTML should look like this for sibling error containers:

 <div class="form_element_container">
    <label for="email">Email <span class="required">*</span></label>
    <input id="email" type="email" name="email" value="0" />
    <div class="error">*Only specific characters allowed!</div>
</div>

Upvotes: 3

Related Questions