Scorpio
Scorpio

Reputation: 1171

Don't want decimal value in the input field

I dont want to allow the decimal values in text box.. I have written the code but it works only if you remove the whole value and then reinsert it.. My issue is when I try to edit the existing value it take the decimal numbers.. Here's the jsfiddle. This is code for reference:

HTML

<input id="Amt"  type="text" value="$78.00">

jQuery

 $(document).ready(function () {

    $("#Amt").keydown(function (e) {
        if ((!e.shiftKey && !e.ctrlKey && !e.altKey) && ((e.keyCode >= 48 && e.keyCode <= 57) ||
                (e.keyCode >= 96 && e.keyCode <= 105))) {
        }
        else if (e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 37 && e.keyCode != 39 &&
                     e.keyCode != 9) {
            e.preventDefault();
        }
    });

   $("#Amt").keyup(function (e) {
        var value = $(this).val();
       var newValue = parseFloat(value).toFixed(2);
        if (!isNaN(newValue)) {
            $(this).val(newValue);
            $(this).caret(newValue.length - 3, newValue.length - 3);
        }
    });
});

Upvotes: 0

Views: 2854

Answers (3)

robC
robC

Reputation: 2737

You can use string methods to chop out the decimal and re-append '.00' if you want to keep this format.

  $("#Amt").blur(function (e) {
    var value = this.value.replace(/\$/g,"");
    var dotPos = value.indexOf(".");
    var dollars = dotPos>-1?value.substring(0,dotPos):value;
    $(this).val(dollars+".00");
  });

  $("#Amt").blur();

http://jsfiddle.net/ZUj8M/14/

Upvotes: 1

algorhythm
algorhythm

Reputation: 8728

why not parsing the given value to Integer?

var newValue = parseInt(floatValue, 10);

then allow the users to insert a dot "." and on .blur()-event you can parse the float to int...

$("#Amt").blur(function() {
    $this.val(parseInt(jQuery(this).val(), 10));
});

Upvotes: 0

Kevin B
Kevin B

Reputation: 95023

I would go about it in a completely different way, just prevent the decimal from getting there in the first place. http://jsfiddle.net/ZUj8M/7/

$(document).ready(function () {

  var timer;
  $("#Amt").on("keydown paste input",function (e) {
    var el = this,
      origval = this.value;
    clearTimeout(timer);
    timer = setTimeout(function () {
      if (origval != el.value && /\./.test(el.value)) {
        el.value = origval;
        alert("Decimals are not allowed in this field.");
      }
    }, 0);
  });
  if (/\./.test($("#Amt").val())) {
    $("#Amt").val($("#Amt").val().replace(/\./g,""));
  }

});

alternatively you could instead of undoing the change, simply remove the decimal.

// el.value = origval;
// alert("Decimals are not allowed in this field.");
el.value = el.value.replace(/\./g,"");

Upvotes: 0

Related Questions