Number only input box with range restriction - javascript

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 = '';
}
});

Related

Don't let to write a number greater than max attribute in input

document.querySelector("#maca").addEventListener("keydown", function(e) {
if (e.target.value > this.getAttribute("max")) {
e.preventDefault();
}
})
<input type="text" name="maca" placeholder="maca" id="maca" max="7">
I'm trying to stop the user from entering a number greater than the value of the max attribute. What is happening is that first the user is allowed to write a larger number then not.
How can I fix this?
Thanks a lot!
It's trickier than it looks, because even <input type="number" max="7"/> allows you to input 9 without complaining (I believe it should complain and block the input, but for some reason does not). Example below
<input type="number" max="7"/>
I came up with this little JS solution :
const max = +maca.getAttribute("max");
maca.addEventListener("keydown", function(e) {
const typed = +e.key;
if(!isNaN(typed)) e.preventDefault(); // Allow any non-number keys (backspace etc.)
if ( +(e.target.value + typed) <= max) {
maca.value += typed
} else {
console.log(`Number too big! Max is ${max}`)
}
})
<input type="number" name="maca" placeholder="maca" id="maca" max="7">
This really won't allow the user to type 8 or 9. Also, you can type 1 but then you can't add another digit to type 11.

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

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.

check if input is between two int or float then display or not display content

In javascript I need to check whiwh value user enter in an html input like this:
<input type="text" id="volume" class="form-control" name="voilume"></input>
<div id"button"></div>
Ineed to know if the input is between 0,5 and 8 (so I have int and float as you can understand).
So the value has to be >= 0,5 and <= 8
If value input if between 0,5 and 8 I have to display a button, else nothing to do. But I need to prevent if user change the value many times.
So if he enters 3 display a button in div id=button", if it changes for another value like 2 for example keep displaying the button, but if he changes value input for 100 I need to remove the button in div id="button".
for now I tried something like this in order to test if it works:
var input= $('#volume').val();
if (input >= 0.5 && input <= 8) {
$('#button').html('ok');
} else {
$('#button').empty();
}
But it does not work.
You can exploit the CSS Constraint Validation here a little bit. It seems to me like a X/Y Problem. Actually, we could set our min, max and step values for this <input> element and then let the browser do the validation:
<input type="number" min="0.5" max="8" step="0.1" required id="volume" class="form-control" name="voilume">
Alongside this, we can make usage of the pseudo css selectors :valid and :invalid like so:
input:valid~div#button {
display: block;
}
input:invalid~div#button {
display: none;
}
This would have the effect, that if we enter a valid value in our input control, the button will be displayed. If not, the button disappears. Magic!
Example: https://jsfiddle.net/4q1fjqwp/
.val() of an input field is a string, you have to convert it to a number in order to be able to compare it to numbers by >=, <=. You also had a typo: id"button"
function go() {
var input=parseFloat($('#volume').val(), 10);
if (input >= 0.5 && input <= 8) {
$('#button').html('ok');
} else {
$('#button').empty();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="volume" class="form-control" name="voilume"/>
<div id="button"></div>
<button onclick="go()">run</button>
The problem may happen when input contain comma ,
so "0,5" >= 0.5 will return false and parseFloat("0,5") will return 0.
You need replace , with .
Something like below will work.
<input type="text" id="myTextField" onblur="change()"/>
<input type="submit" id="byBtn" value="" />
JavaScript
function change() {
var myTextbox = document.getElementById('myTextField').value;
var button = document.getElementById('byBtn');
if (parseFloat(myTextbox) >= 0.5 && parseFloat(myTextbox) <= 8) {
button.value = "OK";
} else {
button.value = "";
}
}
you need to parse string value to integer. for that use parseInt().
it will parse string to integer.
replace this:
var input= $('#volume').val();
by
var inputval= parseInt($('#volume').val());

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