Html input field set maximum value [duplicate] - javascript

This question already has answers here:
How to prevent inserting value that is greater than to max in number field in html
(2 answers)
Closed 5 years ago.
the max property does not work if i put a number in the field. Why?
it works only when i change the value with the arrows.
JS Fiddle
HTML
<input id= "0" class='labelmax form-control'
type='number' name='max_label' min='0' max='99' value='1'>

With HTML5 max and min, you can only restrict the values to enter numerals. But you need to use JavaScript or jQuery to do this kind of change. One idea I have is using data- attributes and save the old value:
$(function () {
$("input").keydown(function () {
// Save old value.
$(this).data("old", $(this).val());
});
$("input").keyup(function () {
// Check correct, else revert back to old value.
if (parseInt($(this).val()) <= 99 && parseInt($(this).val()) >= 0)
;
else
$(this).val($(this).data("old"));
});
});

For it work automatically you have to wrap your input within a form and add a submit button to that form
If you don't want to wrap it in a form and want maximum customisation you'll have to use Javascript and setup an event handler that will listen for user input and act accordingly

You can use something like below by making use of simple JavaScript. In your code I dont see any JS.
document.getElementsByClassName('labelmax form-control')[0].oninput = function () {
var max = parseInt(this.max);
if (parseInt(this.value) > max) {
this.value = max;
}
}
<input id= "0" class='labelmax form-control' type='number' name='max_label' max='99' value='1'/>

Related

validate input with a number range with on keypress event Jquery

I have the following situation.I have an input and I need that as I write I validate that the value of that input is between 1 and 100. The function cannot allow to write a number greater than 100. In my code I get that validation done but it only works when I write the fourth character, then it does not let me write anything else, I need that if I have 2 characters in the input, I will not be allowed to write a third because the number would be greater than 100, I should only write a third character if the written numbers are 1 and 0, that is 10.
<input type="text" class="porciento" name="">
$(document.body).on("keypress", ".porciento", function (event) {
var numero=$(this).val();
if($(this).val()>100){
event.preventDefault();
}
});
$(document.body).on("keypress", ".porciento", function (event) {
var numero=$(this).val();
if($(this).val()>100){
event.preventDefault();
}
});
<input type="text" class="porciento" name="">
Here you go... you may personalize it as you want, but this is the logic.
document.getElementsByTagName('input')[0].addEventListener('keydown', (e) => {
const val = parseInt(e.target.value + e.key);
if (!isNaN(val) && val > 100) {
e.preventDefault();
}
}, {passive: false, capture: true});
<input type="text" name="myInput">
Two important factors to consider when performing range number validation during keypress;
When the value in input textbox is NOT SELECTED, the real outcome should be (input.value * 10) + parseInt(e.key) and not simply input.value + parseInt(e.key). It should be * 10 because you add one more digit at the back during keypress, e.g. 10 becomes 109.
When the value in input textbox IS SELECTED, you can simply check if Number.isInteger(parseInt(e.key)) because when 100 is selected, pressing 9 will not turn into 1009 but 9 instead.
You can checkout my answer here for further explanation and change a little bit of the code to suit your need.

How to catch space bar event from input type number using javascript [duplicate]

This question already has answers here:
Changing the keypress
(7 answers)
Closed 5 years ago.
How to catch space bar input from input type like this:
<html>
<head>
<script type = "text/javascript">
function lala(aa){
console.log(aa + " dasda");
}
</script>
</head>
<body>
<input type = "number" value = "0.00" class = "no-spin" onchange='lala(this)' />
</body>
</html>
onchange does not trigger the space bar input. I would like to change the value to 0 again when space bar is pressed.
Do you want something like this ?
I change type to text from number to allow space
I remove onchange event and created addEventListener to watch keyup
Instead value you should keep 0.00 in placeholder to make better user friendly.
document.body.addEventListener("keyup", function(e){
if(e.keyCode == 32){
document.querySelector("#test").value = '';
}
});
<input type="text" placeholder="0.00" value="" class="no-spin" id="test" />
Use keyup event to catch every change to the input field (you'll need to give the input field an id):
document.getElementById('input-id').addEventListener('keyup', function(e) {
// everything will be available here
});
you shouldn't declare javascript events as html attributes. it's bad practice
The change event is only fired when the input looses focus, not on each keystroke.
The input event does, for any valid input (and space isn't one in this case).
You can use keyup and then do your thing:
<input type="number" value="0.00" class="no-spin" onkeyup="lala(event, this)" />
You can check aa.keyCode == 32 (aa being your "lala" argument name) to know if the key pressed was the spacebar, and then do your thing.
Something like this if you want this to happen when the value is empty:
function lala(event, input) {
if (event.keyCode == 32 && !input.value) {
input.value = '0.00';
}
}

Restrict character/string/word in input

My function, addthisTxt, is not checking the length. It should not exceed 11. Below is what I have tried so far; I'd like to keep on adding text until it reaches the max length, otherwise it should restrict the user from adding more.
HTML
<input type="checkbox" name="chkbxr" value="add this offer on wrapper"
(change)="addthisTxt($event.target.getAttribute('txt'), $event.target.checked)">
JavaScript
addthisTxt(txt, checked): void {
if (checked) {
if((this.v.offerName.length +txt.length) >= 55){
this.v.offerName = this.v.offerName + txt;
}
this.v.offerName = this.v.offerName;
}
}
You are setting the value on this.v.offerName. The UI element is not bound to this JavaScript variable and you need to set the value of the UI input element to restrict the value.

HTML5 : Input field with the type of 'number' will still accept higher value than its 'max' using keyboard inputs

Hello guys need some help here. i want to have limit the numbers inputted in my input field by putting max attribute to it. i have no problem with that until i use my keyboard to input data on it. seems like the max attribute is not filtering the input coming from the keyboard.
e.g
<input type="number" max="5" />
i can't go until 6 using the up and down arrow but when i manually put 6 using keyboard it's accepts it. how can i prevent? thank you
You would need to use JavaScript to do it. This will not let the user enter a number higher than 5:
<input type="number" max="5" onkeyup="if(this.value > 5) this.value = null;">
Another possible solution is to completely block the keyboard input by replacing onkeyup=".." event in the code above with onkeydown="return false".
have no problem with that until i use my keyboard to input data on it.
seems like the max attribute is not filtering the input coming from
the keyboard
This is how HTML5 validation/constraint work. However, it will invalidate when the form submits. Alternatively, you can validate it yourself. To validate yourself, you need to wire up Javascript and call the checkValidity() on the input element.
checkValidity() of the constraints API will check the validity state of the element and will return the state of whether the input element validate or not. This will also set the validity object on the input so that you can query more details.
Ref: https://html.spec.whatwg.org/multipage/forms.html#constraints and https://html.spec.whatwg.org/multipage/forms.html#form-submission-algorithm
You can also use the :invalid selector in CSS to highlight invalid inputs.
Example Snippet:
var input = document.getElementById('test'),
result = document.getElementById('result');
input.addEventListener('blur', validate);
function validate(e) {
var isValid = e.target.checkValidity();
result.textContent = 'isValid = ' + isValid;
if (! isValid) {
console.log(e.target.validity);
}
}
input[type=number]:invalid {
border: 2px solid red;
outline: none;
}
<label>Enter value and press tab: </label><br/>
<input id="test" type="number" min="1" max="10" />
<hr/>
<p id="result"></p>
You can use javascript to restrict the maximum input value to 5.
HTML
using oninput as a event handler
<input type="number" max="5" oninput="checkLength(this)" />
JS
function checkLength(elem) {
// checking if iput value is more than 5
if (elem.value > 5) {
alert('Max value is 5')
elem.value = ''; // emptying the input box
}
}
DEMO
An Utility Function to Solve Two Problem
Problem 1: Limit user input to maximum n digit
For this use n number of 9 as max parameter. As an example if you want to limit user input in 4 digit then max param value will be 9999.
Problem 2: Limit user input at a maximum value
This is intuitive. As an example If you want restrict the user input to maximum 100 then max param value will be 100.
function getMaxInteger(value, max) {
if(!value) return;
if( parseInt(value) <= max ) {
return value;
}
return getMaxInteger(value?.substr(0, value?.length-1), max);
}
function maxInt(value, max) {
return getMaxInteger(value?.replace(/\D/,''), max);
}
Use this maxInt method on input change handler
ngModelChange for Angular
onChange for React
v-on:change or watch for Vue
onkeyup="if(this.value > <?=$remaining?>) this.value = null; else if(this.value < 1) this.value = null;"

unchangeable leading characters in HTML input? [duplicate]

This question already has answers here:
How can I add an unremovable prefix to an HTML input field?
(18 answers)
Closed 6 years ago.
How do I generate an input element that has a default starting value in there that is unchangeable? For example, I am looking for a number from the user but I want '333' to be already in the input text box since all inputs will start with that number. I also don't want the user to be able to change it. I need the 333 to be part of the value also rather than just being added via style since I need to do validation on it.
I'd use 2 inputs as William B suggested but I'd consider whether to use the disabled attribute or the readonly attribute. The disabled attribute won't allow the first input to be focused and the default browser styling will give it a gray background. The readonly attribute will allow it to be focused and may have a more desirable initial styling.
One possibilty using JavaScript:
nine = document.getElementById("nine");
nine.addEventListener("keydown", function (ev) {
var el = this;
var value = el.value;
setTimeout(function () {
if (el.value.indexOf("333") != 0) {
el.value = value;
}
}, 0);
});
<input type="text" value="333" id="nine" />
I'd suggest using 2 inputs that look like a single input, with the first one readonly. See this fiddle: https://jsfiddle.net/39whrqup/2/
<input readonly value="333" class="static-input">
<input class="nonstatic-input">
.static-input {
margin-right: -20px;
width: 50px;
border: 0;
}
.nonstatic-input {
border: 0;
}
When reading the user input you will have to prepend the static portion, naturally:
var userInput = document.querySelector('input.static-input').value +
document.querySelector('input.nonstatic-input').value;

Categories