Monday, September 18, 2017

JQuery Hints

Allow only two numbers after decimal point using JQuery

The requirement is to allow users to enter only two numbers after decimal point using JQuery
  • Has the user entered decimal point?
  • Are the decimal places more than two?

Solution:
  1.  You can use $(this).val().indexOf('.') != -1
  2. You can use $(this).val().substring($(this).val().indexOf('.'), $(this).val().indexOf('.').length).length > 2
 
      Example:

<html>

<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>

<body>
<div class="Title">Welcome!</div>

<div>
<input id="my-bill-value" type="text" placeholder="10.00">
<span>$</span>
</div>
</body>
<script language="javascript">
// Decimal check - Start
$('#my-bill-value').keypress(function (event) {
var $this = $(this);
if ((event.which != 46 || $this.val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}

var text = $(this).val();
if ((event.which == 46) && (text.indexOf('.') == -1)) {
setTimeout(function () {
if ($this.val().substring($this.val().indexOf('.')).length > 3) {
$this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
}
}, 1);
}

if ((text.indexOf('.') != -1) &&
(text.substring(text.indexOf('.')).length > 2) &&
(event.which != 0 && event.which != 8) &&
($(this)[0].selectionStart >= text.length - 2)) {
event.preventDefault();
}
});

$('#my-bill-value').bind("paste", function (e) {
var text = e.originalEvent.clipboardData.getData('Text');
if ($.isNumeric(text)) {
if ((text.substring(text.indexOf('.')).length > 3) && (text.indexOf('.') > -1)) {
e.preventDefault();
$(this).val(text.substring(0, text.indexOf('.') + 3));
}
}
else {
e.preventDefault();
}
});
// Decimal check - End
</script>

</html>