How can I validate only the numbers 0 to 10?
I have this function which validate all the numbers.
function compruebacampo(e, campotexto) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
}
Thanks a lot for your help.
http://jsfiddle.net/6faHh/
The best JavaScript is no JavaScript.
<input type="number" min="0" max="10" />
<input id="your_input_id1" type="number" min="0" max="10" />
<input id="your_input_id2" type="number" min="0" max="10" />
<script>
var input1 = document.getElementById("your_input_id1");
var input2 = document.getElementById("your_input_id2");
function testNums(evt) {
var num = parseInt(evt.target.value, 10);
if (typeof num === "number" && num < 11 && num > -1) {
evt.target.value = num
} else {
evt.target.value = ''
}
};
input1.onkeyup = testNums;
input2.onkeyup = testNums;
</script>
Example js fiddle
http://jsfiddle.net/g63b5/3/
In this example entry is prevented and the box is cleared if the range is incorrect or anything other than number entered, also uses native html5 input for supported devices.
Edit: wasn't 100% sure what your comment meant, so I just added the handler to more inputs, in case that is what you were asking.
Related
I have input:
<input type="number" step="1" min="0" max="4" />
How can I display alert that max value is 4 when user clicks on up arrow and current value is already 4?
Try this
You have to tell the field it was already clicked and reached 4 before alerting next time
Browser that respect the max=4 will not allow the field to increment beyond 4 so the value on its own is not enough
document.getElementById("num").addEventListener("click", function(e) {
const value = this.value,
max = this.getAttribute("max"),
min = this.getAttribute("min"),
minned = this.dataset.minned === "true";
maxed = this.dataset.maxed === "true";
if (value === max && maxed) {
alert("Value is max");
}
if (value === min && minned) {
alert("Value is at 0");
}
this.dataset.maxed = value === max ? "true" : "false";
this.dataset.minned = value === min ? "true" : "false";
})
document.getElementById("num").addEventListener("input", function(e) {
const value = this.value || 0,
min = this.getAttribute("min"),
max = this.getAttribute("max");
if (value != "" && value > max || value < min) {
alert(`Value should be between ${min} and ${max}`);
this.value = "";
}
this.dataset.maxed = value === max ? "true" : "false";
this.dataset.minned = value === min ? "true" : "false";
})
<input id="num" type="number" step="1" min="0" max="4" />
As far as I can guess from your information adding an eventlistener would do what you want to:
const input_number = document.getElementById("input_number");
input_number.addEventListener("change", function(){
if(input_number.value > 4) {
alert("Max. number is 4!")
}
})
<input id="input_number" type="number" step="1" min="0" max="4" />
Try this
function handleMyInput(event){
const { value, max } = event.target
if(value >= max) alert('Max value reached');
}
<input type="number" step="1" min="0" max="4" id='myInput' onclick='handleMyInput(event)' />
I am doing some validations for the input type.
<input
type="number"
min="0"
decimal-places=""
ng-model="candidate.ctc"
class="form-control ng-pristine ng-untouched ng-valid-min ng-invalid ng-invalid-required candidateCTCInputPosition"
id="ctc"
placeholder="CCTC"
autocomplete="off"
required="">
Here, with this user is not able to take the 0 as an input, So, when user types the 0 then it is treating it as a false value.
So, user should not be able to type negative values using the keyups and also it should accept the 0. How can I achieve this?
Here's a working solution:
http://jsfiddle.net/qoL16sup/
Directive:
decimalPlaces.$inject = ['$filter','$locale'];
function decimalPlaces($filter,$locale){
return {
require: 'ngModel',
link: function(scope,element,attrs,ngModelCtrl){
var groupSep = $locale.NUMBER_FORMATS.GROUP_SEP;
var decimalSep = $locale.NUMBER_FORMATS.DECIMAL_SEP;
var decimalPlaces = scope.$eval(attrs['decimalPlaces']) || 0;
var pattern = decimalPlaces > 0 ?
new RegExp('^\\d*(\\'+ decimalSep +')?[0-9]{0,' + decimalPlaces + '}$') : new RegExp('^\\d*$');
element.bind('keypress',function(e){
var lastChar = e.charCode!==0?String.fromCharCode(e.charCode):'';
var selectionStart = element[0].selectionStart;
var selectionEnd = element[0].selectionEnd;
var newVal = element.val().slice(0,selectionStart) + lastChar + element.val().slice(selectionEnd);
if(!pattern.test(newVal)){
e.preventDefault();
}
});
element.bind('blur',function(){
var value = ngModelCtrl.$viewValue || ngModelCtrl.$modelValue;
if (ngModelCtrl.$isEmpty(value)) return null;
if(pattern.test(value)){
element.val($filter('number')(value,decimalPlaces));
}else{
element.val('');
ngModelCtrl.$setViewValue('');
ngModelCtrl.$commitViewValue();
}
});
element.bind('focus',function(){
var value = ngModelCtrl.$modelValue || ngModelCtrl.$viewValue;
if (ngModelCtrl.$isEmpty(value)) return null;
element.val(value);
});
ngModelCtrl.$parsers.unshift(function(value){
if (ngModelCtrl.$isEmpty(value)) return null;
if(pattern.test(value)){
value = parseFloat(value);
if(decimalPlaces){
value = value.toFixed(decimalPlaces);
}else{
value = Math.floor(value);
}
return parseFloat(value);
}else{
return null;
}
});
if (angular.isDefined(attrs.min)) {
var minVal = scope.$eval(attrs.min);
ngModelCtrl.$validators.min = function(value) {
return ngModelCtrl.$isEmpty(value) || angular.isUndefined(minVal) || value >= minVal;
};
}
if (angular.isDefined(attrs.max)) {
var maxVal = scope.$eval(attrs.max);
ngModelCtrl.$validators.max = function(value) {
return ngModelCtrl.$isEmpty(value) || angular.isUndefined(maxVal) || value <= maxVal;
};
}
}
}
}
HTML:
<form name="myForm" novalidate autocomplete="off">
<label>
Decimal places = 0
<input
type="text"
name="input1"
decimal-places="0"
ng-model="model.input1"
autocomplete="off"
required>
</label>
<br/> <br/>
<lable>
Decimal places = 2:
<input
type="text"
name="input2"
decimal-places="2"
ng-model="model.input2"
autocomplete="off"
required>
</lable>
<br/> <br/>
<lable>
Decimal places = 2, min = 100, max = 10000:
<input
type="text"
name="input3"
decimal-places="2"
min="100"
max="10000"
ng-model="model.input3"
autocomplete="off"
required>
</lable>
</form>
You can use ngPattern to validate the input. But it won't prevent the user from typing a negative number. Use a following function to avoid typing a negative value.
$(document).ready(function(){
$("#ctc").keydown(function(e){
if (e.key == "." || e.key=="-") {
e.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Preventing negative values</p>
<input type="number" min="0" max="10" decimal-places="" ng-model="candidate.ctc" class="form-control ng-pristine ng-untouched ng-valid-min ng-invalid ng-invalid-required candidateCTCInputPosition" id="ctc" placeholder="CCTC" autocomplete="off" style='width:300px' required=""/>
You should use like this,
var number = document.getElementById('ctc');
number.onkeydown = function(e) {
if(!((e.keyCode > 95 && e.keyCode < 106)
|| (e.keyCode > 47 && e.keyCode < 58)
|| e.keyCode == 8)) {
return false;
}
}
I everyone I have a text-box
Number : <input type="text" name="Number" placeholder="MH03AH6414" id="txtRegNo" />
<span id="errmsg"></span>
The text-box must take value like the placeholder input(1st two character alphabet (a-z or A-Z) 2nd two character number (0-9) the 3rd two character alphabet (a-z or A-Z) and last four character number (0-9)
I have tried to do with key-press event and all but not formed properly
$("#txtRegNo").keypress(function (e) {
var dataarray = [];
var dInput = $(this).val();
for (var i = 0, charsLength = dInput.length; i < charsLength; i += 1) {
dataarray .push(dInput.substring(i, i + 1));
}
alert(dataarray);
alert(e.key);
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false
}
});
Please help me.
Thanks in advance
I tried of focusout which now works fine with me but I want to prevent from keyinput
Here is the jsfiddle solution
http://jsfiddle.net/ntywf/2470/
Try this out. Modified the function as per requirement
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
Number : <input type="text" name="Number" placeholder="MH03AH6414" id="txtRegNo" />
<span id="errmsg"></span>
<!-- end snippet -->
<script>
$("#txtRegNo").keyup(function (e) {
$("#errmsg").html('');
var validstr = '';
var dInput = $(this).val();
var numpattern = /^\d+$/;
var alphapattern = /^[a-zA-Z]+$/;
for (var i = 0; i < dInput.length;i++) {
if((i==2||i==3||i==6||i==7)){
if(numpattern.test(dInput[i])){
console.log('validnum'+dInput[i]);
validstr+= dInput[i];
}else{
$("#errmsg").html("Digits Only").show();
}
}
if((i==0||i==1||i==4||i==5)){
if(alphapattern.test(dInput[i])){
console.log('validword'+dInput[i]);
validstr+= dInput[i];
}else{
$("#errmsg").html("ALpahbets Only").show();
}
}
}
$(this).val(validstr);
return false;
});
</script>
So basically I have a for loop and I am trying to get it to run x amount of times. Depending on what the user inputs. The issue I am having is how to get the user input and also make sure that its a number not any other type of input. making them try again if its wrong.
It's simple really
Input Number : <input id="numberinput" onkeypress="return event.charCode >= 48 && event.charCode <= 57" />
<button id="btn" onclick="doAction()">
Send
</button>
<script>
var doAction = function () {
var input = document.getElementById('numberinput');
var times = parseint(input.value);
for(var i = 0; i < times; i++) {
//do whatever you need to do
}
}
</script>
In HTML5 you can use <input type="number"> to restrict an input to numeric characters only.
For older browsers, that are not HTML5-compatible, use <input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>. This utilizes Javascript to make sure that only numeric input is accepted into the input box.
Check out the snippet below for both solutions in action:
Javascript-based:<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>
<br><br>
HTML5 solution (preferred):<input type="number">
Fiddle
HTML
<input type="number" id="myInput">
<button id="myButton">Run Loop</button>
Javascript
$('body').on('click', '#myButton', function() {
var input = $('#myInput').val();
for(var i = 0; i < input; i++) {
alert('You have written inside input field: ' + input + ". This is Alert #" + (i+1))
}
});
To get the value from the input, you can use the value property of the input element.
To make sure the input is a number, you can specify type="number" if HTML5 is supported as mentioned in Angelos Chalaris's answer.
document.getElementById('btn').onclick = function(){
var totalIterations = parseInt(document.getElementById('input').value);
var output = document.getElementById('output');
output.innerHTML = '';
for(var i = 1; i <= totalIterations; i ++) {
var item = document.createElement('div');
item.innerHTML = i;
output.appendChild(item);
}
};
<input id="input" type="number"/>
<input id="btn" type="button" value="Do loop"/>
<div id="output"></div>
Here is an example using user input dialog:
var input, parsedInput = 0;
do {
input = prompt("Please enter valid number", "1");
parsedInput = parseInt(input);
} while(isNaN(parsedInput) || parsedInput < 0);
// keep trying on invalid input or negative number
for( i=0; i< parsedInput ; i++){
console.log("loop " + i);
}
HTML:
<input type="text" name="somefield" id="someid" value="10" />
JS:
var userInput = document.getElementById('someid').value;
if( Number.isInteger(parseInt(userInput)) )
{
// do something
}
Also, Number.isInteger() does not work on Internet explorer 11 or earlier.
I want minlength=8 and maxlength=14, how can I achieve this validation.
html:
<input type="text" name="354" id="field">
jQuery:
$("input[name=354]").keypress(function(e){
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("Digits only").show().fadeOut("slow");
return false;
}
});
Now with HTML5 you can use the properties minlength and maxlength.
<input type="text" minlength="8" maxlength="14" name="354" id="field">
You can use HTML5 attributes minlength and maxlength to manage input text length. But if you want to use JQuery to do this work, see this example
var minLength = 3;
var maxLength = 10;
$("input").on("keydown keyup change", function(){
var value = $(this).val();
if (value.length < minLength)
$("span").text("Text is short");
else if (value.length > maxLength)
$("span").text("Text is long");
else
$("span").text("Text is valid");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<span></span>