3

I am unable to edit the text field when selected with mouse.

I tried with keypress event in jquery for restricting two decimal places after decimal point.

$('.decimal').keypress(function (e) {
    var character = String.fromCharCode(e.keyCode)
    var newValue = this.value + character;
    if (isNaN(newValue) || parseFloat(newValue) * 100 % 1 > 0) {
        e.preventDefault();
        return false;
    }
});

JSFIDDLE

here I am facing a problem on load when I select a text in salary field with mouse I am unable to edit the field, but it is working fine for when the keypress event is triggered.

$(function () {
    $('#name').bind('paste', function () {
        var self = this;
        setTimeout(function () {
            if (!/^[a-zA-Z]+$/.test($(self).val())) $(self).val('');
        }, 0);
    });

    $('#salary').bind('paste', function () {
        var self = this;
        setTimeout(function () {
            if (!/^\d*(\.\d{1,2})+$/.test($(self).val())) $(self).val('');
        }, 0);
    });

    /*$('.decimal').keyup(function () {
        var val = $(this).val();
        if (isNaN(val)) {
            val = val.replace(/[^0-9]./{2,2}/g,'');


             if(val.split('.').length>2) 
                 val =val.replace(/\. + $ / , "");
        }
        $(this).val(val);
    });*/
    
    $('.decimal').keypress(function (e) {
        var character = String.fromCharCode(e.keyCode)
        var newValue = this.value + character;
        if (isNaN(newValue) || parseFloat(newValue) * 100 % 1 > 0) {
            e.preventDefault();
            return false;
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<b>Name</b>

<input type="text" id="name" />
<br/>
<b>Salary</b>

<input type="text" id="salary" class="decimal" />
mplungjan
  • 169,008
  • 28
  • 173
  • 236
pbsbr
  • 385
  • 3
  • 12

0 Answers0