How can I keep trailing zeros in a Kendo UI numericTextBox? - javascript

I am trying to build a numeric input widget using Kendo UI. I am able to set the format so that trailing zeros are not truncated when the field does not have focus, but when the field does have focus, the trailing zeros disappear.
I have an example at http://dojo.telerik.com/eBevU and the relevant bits are listed below:
<div id="add-product" class="demo-section k-content">
<ul id="fieldlist">
<li>
<label for="numeric">Input</label>
<input id="numeric" type="number" value="17" min="0" max="100" step="1" style="width: 100%;" />
</li>
</ul>
</div>
<script>
$(document).ready(function() {
// create NumericTextBox from input HTML element
$("#numeric").kendoNumericTextBox({
format: "n5",
decimals: 5
});
});
</script>
This example shows "17.00000" in the input box before it has focus, and "17" after.

The only solution I found is to basically reconstruct the value using the format specified in the widget configuration i.e. adding the decimal separator (if needed) and the missing trailing zeros. Bind the function below to the focus event of the input.
function () {
var input = $(this);
var widget = input.data("kendoNumericTextBox");
setTimeout(function () {
if (widget !== undefined && input.val() !== "") {
var format = widget._format(widget.options.format);
var decimals = widget.options.decimals;
if (decimals > 0) {
var inputValue = input.val();
var digits = inputValue.split(format["."]);
if (digits.length == 1)
inputValue = inputValue + format["."];
var l = digits[0].length + 1 + decimals;
while (inputValue.length < l)
inputValue = inputValue + "0";
input.val(inputValue);
}
}
}
}
You can find here your example modified.

The only way (that I have experienced) kendo will retain the decimal places when focused is if the number already has a value with the specified precision, otherwise it removes them. You could try and modify the step so that the user can increase the value by smaller amounts.
$("#numeric").kendoNumericTextBox({
format: "n5",
decimals: 5,
step: 0.00001
});
Good luck.

Related

html <input type="text" /> number-only with min and max value

I'm trying to get the min="" and max="" attributes working on a number only input. Using <input type="number"> is out of the question due to terrible browser support for localization (dots should be thousand seperators, comma as decimal seperator, in input as well as in submit).
Optimally, upon form submit of every form, it would check for those certain fields if the number follows the pattern and is in the correct range, just like it would do natively for a type="number" input.
Alternatively, if it's possible or easier, I'm also open to using <input type="number" /> as long as pattern, currency signs and most importantly, commas are accepted in BOTH the value="123,12", the user input AND the value submitted to the server.
So far, I use pattern="-?(\d+|\d{1,3}(\.\d{3})*)(,\d+)?" which already validates the input except for min and max values.
Expected behaviour is that on a <input type="text" pattern"-?(\\d+|\\d{1,3}(\\.\\d{3})*)(,\\d+)?" min="0" max="1500" /> it would let me input any value I want, but when submitting the form, check if the numerically parsed value of the field (omitting currency signs or dots, understanding commas as decimal) is in the range between 0 and 1500. Optimally, but this doesn't matter as much, I'd also like the increment and decrement arrows with a step="0.01" such as for type="number" inputs.
Sadly, I'm completely out of ideas on how to implement this on a per-field basis and not run global javascript on each form submisssion button, preventing the default if not every input matches the criteria. But even if I did that, how would I go about displaying the correct (localized) warnings that type="number" would give me?
$("input[data-type='currency']").on({
keyup: function() {
formatCurrency($(this));
},
blur: function() {
validateCurrency($(this));
formatCurrency($(this), "blur");
}
});
function validateCurrency(input){
var c = parseFloat(input.val().replace(/\,|$/g,'').replace('$',''));
if(c<input.attr('min')){
input.val(input.attr('min'));
}else if(c>input.attr('max')){
input.val(input.attr('max'));
}
}
function formatNumber(n) {
// format number 1000000 to 1,234,567
return n.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")
}
function formatCurrency(input, blur) {
// appends $ to value, validates decimal side
// and puts cursor back in right position.
// get input value
var input_val = input.val();
// don't validate empty input
if (input_val === "") { return; }
// original length
var original_len = input_val.length;
// initial caret position
var caret_pos = input.prop("selectionStart");
// check for decimal
if (input_val.indexOf(".") >= 0) {
// get position of first decimal
// this prevents multiple decimals from
// being entered
var decimal_pos = input_val.indexOf(".");
// split number by decimal point
var left_side = input_val.substring(0, decimal_pos);
var right_side = input_val.substring(decimal_pos);
// add commas to left side of number
left_side = formatNumber(left_side);
// validate right side
right_side = formatNumber(right_side);
// On blur make sure 2 numbers after decimal
if (blur === "blur") {
right_side += "00";
}
// Limit decimal to only 2 digits
right_side = right_side.substring(0, 2);
// join number by .
input_val = "$" + left_side + "." + right_side;
} else {
// no decimal entered
// add commas to number
// remove all non-digits
input_val = formatNumber(input_val);
input_val = "$" + input_val;
// final formatting
if (blur === "blur") {
input_val += ".00";
}
}
// send updated string to input
input.val(input_val);
// put caret back in the right position
var updated_len = input_val.length;
caret_pos = updated_len - original_len + caret_pos;
input[0].setSelectionRange(caret_pos, caret_pos);
}
input {
border: 2px solid #333;
border-radius: 5px;
color: #333;
font-size: 32px;
margin: 0 0 20px;
padding: .5rem 1rem;
width: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="currency-field" id="currency-field" pattern="^\$\d{1,3}(,\d{3})*(\.\d+)?$" value="" data-type="currency" min="1000" max="1000000" placeholder="$200,000.00">
Minimum: 1000, Maximum: 1,000,000
Code by: Wade Williams #559wade
Tweaks: I just added validateCurrency() function and executed it on blur event to check for min and max

Showing prefix code for phone numbers - Jquery

I have implemented jQuery International Telephone Input but the issue now is, when i select the country, the prefix code doesn't show. How can i achieve this please ?
View
<div class="form-group">
<label for="eventRegInput2">Phone Number</label>
<input type="tel" id="phone" class="form-control square" placeholder="" value="{{ old('phone') }}"name="phone" required>
</div>
JS code responsible for displaying the prefix of the country selected.
JS
// get the input val, adding the dial code if separateDialCode is enabled
_getFullNumber: function() {
var val = $.trim(this.telInput.val()), dialCode = this.selectedCountryData.dialCode, prefix, numericVal = this._getNumeric(val), // normalized means ensure starts with a 1, so we can match against the full dial code
normalizedVal = numericVal.charAt(0) == "1" ? numericVal : "1" + numericVal;
if (this.options.separateDialCode) {
prefix = "+" + dialCode;
} else if (val.charAt(0) != "+" && val.charAt(0) != "1" && dialCode && dialCode.charAt(0) == "1" && dialCode.length == 4 && dialCode != normalizedVal.substr(0, 4)) {
// if the user has entered a national NANP number, then ensure it includes the full dial code / area code
prefix = dialCode.substr(1);
} else {
prefix = "";
}
return prefix + val;
},
How can I achieve this please?
Assuming that your function is working (that format properly input text with area code, all you have to do is when user leave textbox you can call your function to format number. This snippet need also to check if user has input something in textbox and if it is a valid code. Apart from that this is the way to ensure that your format function run everytime user leaves textbox and update its value with output from your function.
$('#phone').on('blur', function() {
var value = $(this).val();
if(value) {
$(this).val(_getFullNumber());
}
});

Number only input box with range restriction

I know that you can use <input type="number"> to restrict a text box to integer only input. However, I was wondering if there is a possibility of range restricting this as well? The limiting factor being without using a javascript function to check it on every keyup. That seems a little heavy and unnecessary. I would think HTML5 would have something built in to take care of this edge-case, but I haven't been able to find anything.
For example, I have an input box for a deduplication ratio where I want to restrict the user to inputting numbers (integer or float) between 3 and 7.
I have a option-select dropdown currently with whole and half numbers, but this does not provide the level of detail I'm looking for.
As I mentioned in the comments earlier... there isn't anything that is HTML only here (you'd think there should be). But... since you did include Javascript and jQuery in your question, I'll propose this simple and light solution.
Assuming this HTML...
<form>
<input type="number" min="3" max="7" step="0.5"></input>
</form>
Then we can use this script to handle our requirements.
$( document ).ready(function() {
$('input').change(function() {
var n = $('input').val();
if (n < 3)
$('input').val(3);
if (n > 7)
$('input').val(7);
});
});
Basically, after the change event fires, we do a quick check to make sure the values are within the guidelines, and if not, force them back within range.
Here's a simple solution for checking that an input is an integer number contained in a given range using the HTML5 constraint validation API that is supported by most browsers:
<label for="n">Enter integer number 1≤n≤10</label>
<input type="number" min="1" max="10" step="1" id="n" oninput="(validity.valid)||(value='');">
To validate and auto-correct the input depending on validity states rangeOverflow, rangeUnderflow, stepMismatch:
<label for="numberSize">Enter integral number 1≤n≤10</label>
<input type="number" min="1" max="10" id="numberSize" oninput="(!validity.rangeOverflow||(value=10)) && (!validity.rangeUnderflow||(value=1)) &&
(!validity.stepMismatch||(value=parseInt(this.value)));">
This will send
all inputs >max to max
inputs < min to min
and truncate decimal values.
<input type="number" min="3" max="7" step="0.01"></input>
step helps restrict the minimum number granularity.
The HTML form element for number is in my humble opinion, poorly designed. It only takes integers so if you wanted a zero at the beginning or two zeros (in the case of a 24 hour system) it's impossible. Other drawbacks are no restrictions to the input when typing in the field so you can add letters, symbols etc. or completely ignore any HTML defined number ranges which pretty much defeats the purpose.
On the other hand, the HTML form element for text allows us to restrict the number of characters (maxlength) which I have done in the example below.
The JS first restricts the inputs to numbers only and then targets the class names rather than all input elements, so the range can be specified when and where you need it.
Rather than set a number if the input is out of the specified range, I opted to delete the field entirely as this will be more obvious to the user that they have made a mistake and less infuriating as it's highly unlikely that setting a specific value will equate to the value that they had in mind.
Used in conjunction with jQuery 3.4.1
JSFiddle link: https://jsfiddle.net/u2smwbgL/1/
HTML
<h1>Set Hours & Minutes</h1>
<div class='left'>
<label> Hours
<input type="text" class='hour' maxlength="2" />
</label>
</div>
<div class='break'></div>
<div class='left'>
<label> Minutes
<input type="text" class='minute' maxlength="2" />
</label>
</div>
Javascript
// Filter Inputs
(function($) {
$.fn.inputFilter = function(inputFilter) {
return this.on("input keydown keyup mousedown mouseup select contextmenu drop",function() {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = "";
}
});
};
}(jQuery));
// Hours & Minutes - Only Numbers
$(".hour,.minute").inputFilter(function(value) {
return /^[0-9]*$/i.test(value);
});
// Hours
$('.hour').on('input', function () {
var value = this.value;
if (value !== '') {
value = parseFloat(value);
if (value > 23)
this.value = '';
}
});
// Minutes
$('.minute').on('input', function () {
var value = this.value;
if (value !== '') {
value = parseFloat(value);
if (value > 59)
this.value = '';
}
});
CSS
.left {position:relative; float:left; width:100%;}
.break {position:relative; float:left; width:100%; height:20px;}
.minute,.hour {position:relative; float:left; width:50px; margin-left:20px; text-align:center;}
$('.minute').on('input', function () {
var value = this.value;
if (value !== '') {
value = parseFloat(value);
if (value > 59)
this.value = '';
}
});

if input field is not a number OR not empty replace with a number

I have an input field that I am monitoring for changes using an .on('input') function as this covers .change and .keyup.
There is no submit button yet I just want to change the behaviour of the input field depending on what is entered.
I will validate server side later and I'm using html5 type='number'.
I only want the field to be able to hold a number, or it can be empty. The user might want to empty the contents to type the number 15 for example.
However I don't want any other characters to be accepted - if they are entered, a prompt should show notifying the user of this and the field is defaulted back to it's starting value of 1.
HTML
<input type="number" class="input-field" placeholder="" value="1" min="1">
JS
$(document).ready(function ($) {
var num = $('input[type="number"]').val();
$('input[type="number"]').on('input', function () {
var num = $(this).val();
if (num < 1 || isNaN(num) || num !== '') {
alert(num + ' is not a number or is less than 1');
$(this).val(1);
}
});
});
I have tried with the above code and it doesn't allow for an empty field. I've also tried if (num < 1 || isNAN(num) || num.length != 0) {
do I need to use .replace() with a Regexr. I've been looking at a few questions on here like here but I'm not sure thats what I'm looking for considering I'm testing for an empty string.
JSFIDDLE
You can use the constraint validation API:
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" class="input-field" placeholder="" value="1" min="1">
However, note that this behavior is obtrusive. If an user types the wrong key, you will annoy him with a modal dialog and will clear the number.
Consider doing nothing. HTML5 browsers won't send the form if the input is not valid.
The HTML5 answer is definitely more elegant.
But if you want to offer more support, this is usually the route I take when trying to verify numbers.
Note that I am using data-min attribute but if you want to switch you can always use $.attr() to grab your min="" attribute.
$(document).ready(function ($) {
$('input[type="number"]').on('change', function () {
var min = parseInt(this.dataset.min),
num = isNaN(parseInt(this.value)) ? 0 : parseInt(this.value),
clamped = Math.max(num, min);
if(num != clamped) {
alert(num + ' is less than 1');
this.value = clamped;
}
});
});
jsfiddle

always want to keep first digit of my textfield as 0

hi guys i have a html form where i have a textfield which is having capabilities to enter two digits the first digit is autopopulated to be 0 and i donot want users to change that hows that possible using javascript or jQuery or anything else.
Here is another way.
the onKeyUp might not be how you want it to work but at least you have some ideas
<script>
window.onload=function() {
document.getElementById('part2').focus();
}
</script>
<form onSubmit="this.realvalue.value='0'+document.getElementById('part2').value">
<input type="text" name="realvalue" value="">This can be hidden<br />
<input type="text" style="border-right:0; width:12px" value="0" readonly="readonly" size="1"><input type="text" id="part2" style="border-left:0; width:13px" size="1" maxsize="1"
onKeyUp="this.value=(this.value.length>1)?this.value.substring(-1):this.value">
<input type="submit">
You can use the event "keyup" triggered when the user enters text in the field:
$('#my-input').keyup(function() {
var theInputValue = $(this).val();
// Do whatever you want with the value (like check its length,
// append 0 at the beginning, tell the user not to change first
// character
//
// Set the real value
$(this).val(newValue);
});
You may be better off with a '0' as text in front of a textbox that can only accept a single digit and then prepend the '0' programmatically?
I wrote and tested this code, and works exactly as you expect:
$(function (){
$('#input_id').bind('input',function (){
var val = $(this).val();
var r = val.match(/^[0][0-9]$/g);
if (r !== null){
val = r[0];
if (val.length === 1){
val = '0' + val;
}
}else{
val = '0';
}
$(this).val(val);
});
});
And works for copy/paste too =]

Categories

Resources