I want to restrict user from giving value less than 163.
I already tried
<input type="text" class="inputnw" name="semesterCode" min="163" value="163" />
I have used text as i dont want to show increment/decrement at the right side of input box.
I want validation for anything below 163 and User can only type numeric number.
You can use this script. Whenever you enter a number less than 163 it will give an alert saying "Number must be less than 163"
function myFunction(){
var x = document.getElementById("number").value;
if ( x.length > 2 && x < 163 ) {
document.getElementById("error").innerHTML = "Please enter a number less than 163"
return false
}else{
return true
}
}
<input type="text" id="number" class="inputnw" name="semesterCode" onkeyup="myFunction()"/>
<span id="error" style="color:red"></span>
Use type=number for the input field! it is really feasible and effective and use the following style to disable the arrows for the input box
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type="number"] {
-moz-appearance: textfield;
}
Sample Plunkr: https://plnkr.co/edit/LaApGngTkJL14mmTmi78?p=preview
Use below Jquery code (Remember i assumed you are using Jquery), Just apply this class "inputnw" for fields you want do this kind of validation.
$(document).ready(function () {
$(document).on('keypress keyup blur', '.inputnw', function (event) {
$(this).val($(this).val().replace(/[^0-9\.]/g, ''));
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(event.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
if ($(this).val().length >= 3) {
if ($(this).val() < 163) {
$(this).val('');
alert('Please enter value greater than 163');
$(this).focus();
}
}
});
$('.inputnw').blur(function () {
if ($(this).val().length < 3) {
if ($(this).val() < 163) {
$(this).val('');
alert('Please enter value greater than 163');
$(this).focus();
}
}
});
});
You could change the type to number and do something like this using the validity object of the input object
<input type="number" class="inputnw" name="semesterCode" min="163" onblur="if(this.validity.rangeUnderflow)this.setCustomValidity('I expect 163');" />
You can add a listener to check the value based on some event. Let the user fix the value themselves and make the message user friendly:
function checkValue(){
var errorEl = document.getElementById(this.id + 'Error');
var message = 'Value must be ' + this.dataset.min + ' or greater';
if (errorEl) {
errorEl.textContent = +this.value >= +this.dataset.min? '' : message;
}
}
window.onload = function() {
var el = document.getElementById('semesterCode');
el.addEventListener('input', checkValue, false);
}
.errorMessage {
color: red;
font-family: sans-serif;
font-size: 80%;
}
<input name="semesterCode" id="semesterCode" data-min="163" value="163"><br>
<span id="semesterCodeError" class="errorMessage">
Related
I am trying to restrict my input box in javascript to have numbers only -999 to 999 with keypress event. But somehow this is failing, can someone help me with this. This is what i have tried so far:-
if(((event.originalEvent.target.value.indexOf("-") > -1) && event.originalEvent.target.value.length === 4) || ((event.originalEvent.target.value.indexOf("-") < 0) && event.originalEvent.target.value.length === 3)) {
event.preventDefault();
}
Use something like this
<input type="number" name="yourName" min="-999" max="999">
You could try something like this:
<script>
function allowRange(min, max, input) {
if(input.value == '-' || (isNaN(input.value) == false && parseInt(input.value) >= min && parseInt(input.value) <= max)) {
//do nothing
}
else {
input.value = '';
}
}
</script>
<input type="text" oninput="allowRange(-999, 999, this);">
It will automatically erase any input not within the range.
My form displays NaN when the input fields are empty. Can you help me to handle this issue? Here’s my code:
function dailyRate () {
var monthlyRate = parseInt(document.getElementById("txt1").value);
var months = 12;
var workingDays = parseInt(document.getElementById("txt2").value);
var totalDailyRate = (monthlyRate * months) / workingDays;
document.getElementById("totalRate").innerHTML = Math.round(totalDailyRate);
}
$(document).ready(function() {
$("#mainForm").submit(function(e){
e.preventDefault();
});
$("#txt2, #txt1").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: Ctrl+C
(e.keyCode == 67 && e.ctrlKey === true) ||
// Allow: Ctrl+X
(e.keyCode == 88 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="mainForm" id="mainForm" action="" onsubmit="return dailyRate()" method="post">
<input type="text" id="txt1" name="text1" placeholder="monthlyrate">
<input type="text" id="txt2" name="text2" placeholder="workingDays">
<p id="alerttext"></p>
<button>Submit</button>
<p id="totalRate"></p>
</form>
The function parseInt() returns NaN if the content is not a number, in your case, if the control is empty, the return of getElementById will return an empty string. So probably you should perform some validation before using it, like:
var monthlyRate = parseInt(document.getElementById("txt1").value);
var months = 12;
var workingDays = parseInt(document.getElementById("txt2").value);
if (isNaN(monthlyRate) || isNaN(workingDays)) {
document.getElementById("totalRate").innerHTML = 'No value';
return;
}
In the example above, if any of the values are invalid, the totalRate will display 'No value'.
Check if the value is NaN or not. If it is NaN, you can set the value to 0 or show an error message:
var textField1 = document.getElementById("txt1");
var textField2 = document.getElementById("txt2");
var monthlyRate = parseInt(textField1.value);
var workingDays = parseInt(textField2.value);
if (isNaN(monthlyRate)) {
textField1.value = 0;
monthlyRate = 0;
}
if (isNaN(workingDays)) {
textField2.value = 0;
monthlyRate = 0;
}
OR:
if (isNaN(totalDailyRate)) {
document.getElementById("totalRate").innerHTML = "Please enter valid numbers";
} else {
document.getElementById("totalRate").innerHTML = Math.round(totalDailyRate);
}
Suggestion: If you use <input type="number">, modern browsers display controls for increasing and decreasing the number in the input field.
I am trying to prevent user from entering 0 in the input box.
HTML code :
<input class="billMenuQuantity" type="number" name="quantity">
Jquery code:
$('.billMenuQuantity').on('keyup keydown', function (e) {
if ($(this).val() < 1 && e.keyCode != 46 && e.keyCode != 8) {
e.preventDefault();
$(this).val(1);
}
});
It's preventing the user from entering the 0 but it's also preventing the user from entering the any other single digit number(i.e 2-9) other than 1.It is accepting the double digit number(i.e 11, 12 etc).
Can any one help me with this?
Just test code === 96 and length of the input-value
$('.billMenuQuantity').on('keyup keydown', function(e) {
var code = e.keyCode || e.which;
if (this.value.length === 0 && code === 96) {
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input class="billMenuQuantity" type="number" name="quantity">
Try this one
$(this).val() == 0 instead of $(this).val() < 1
$('.billMenuQuantity').on('keyup keydown', function (e) {
if ($(this).val() == 0 && e.keyCode != 46 && e.keyCode != 8) {
e.preventDefault();
$(this).val(1);
}
});
Here is the fiddle which will allow only to numbers.
I want to do this in based on id.
So i created this fiddle
$(document).ready(function () {
//called when key is pressed in textbox
$("#quantity").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
How can i do this for a series of id like quantity1,quantity2, like this..
Update :
I can't use class name.. How can i do it only by id
All you've to do is to match all the id's which is simple. See this fiddle.
Here's the part code -
$(document).ready(function () {
//called when key is pressed in textbox
$("[id^=quantity]").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
Demo
Try this
HTML
Number : <input type="text" name="quantity" class= "numberonly" id="quantity1" />
Number1 : <input type="text" name="quantity" class= "numberonly" id="quantity2" />
Number1 : <input type="text" name="quantity" class= "numberonly" id="quantity3" />
<span id="errmsg"></span>
Jquery
$(document).ready(function () {
for(var i = 1; i< 4 ;i++)
{
//called when key is pressed in textbox
$("#quantity"+i).keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
}
});
I have an input field which I want to restrict so that the user only can input a number with the maximum of two decimals. Want to do this using jQuery.
Could I use jQuery toFixed() function somehow?
Thanx!
An alternative approach with a regular expression:
$('#id').on('input', function () {
this.value = this.value.match(/^\d+\.?\d{0,2}/);
});
The id selector can be replaced by a css selector.
$('input#decimal').blur(function(){
var num = parseFloat($(this).val());
var cleanNum = num.toFixed(2);
$(this).val(cleanNum);
if(num/cleanNum < 1){
$('#error').text('Please enter only 2 decimal places, we have truncated extra points');
}
});
Here is a fiddle http://jsfiddle.net/sabithpocker/PD2nV/
Using toFixed will anyhow cause approximation 123.6666 -> 123.67
If you want to avoid approximation check this answer Display two decimal places, no rounding
A HTML5 solution:
<input type="number" step="0.01" />
Demo
If you want to style invalid inputs (some browsers do it by default), you can use :invalid selector:
input:invalid { box-shadow: 0 0 1.5px 1px red; }
Note this approach won't attempt to truncate the number automagically, but if the user enters more than two decimal digits, the input will become invalid, and thus the form won't be submitted:
<input type="text" name="amount1" id="amount1" class="num_fld Amt" onkeypress="return check_digit(event,this,8,2);" size="9" value="" maxlength="8" style="text-align:right;" />
The following function will restrict decimals according to your need of decimal places and also restrict more than one dot
function check_digit(e,obj,intsize,deczize) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) { keycode = e.which; }
else { return true; }
var fieldval= (obj.value),
dots = fieldval.split(".").length;
if(keycode == 46) {
return dots <= 1;
}
if(keycode == 8 || keycode == 9 || keycode == 46 || keycode == 13 ) {
// back space, tab, delete, enter
return true;
}
if((keycode>=32 && keycode <=45) || keycode==47 || (keycode>=58 && keycode<=127)) {
return false;
}
if(fieldval == "0" && keycode == 48 ) {
return false;
}
if(fieldval.indexOf(".") != -1) {
if(keycode == 46) {
return false;
}
var splitfield = fieldval.split(".");
if(splitfield[1].length >= deczize && keycode != 8 && keycode != 0 )
return false;
}else if(fieldval.length >= intsize && keycode != 46) {
return false;
}else {
return true;
}
}
}
$("#myInput").focusout(function() {
if ($(this).val().length > 2 || isNaN(Number($(this).val())) {
alert("Wrong number format");
}
});
Try this for all symbols:
inputField.value.replace(/(\...)(.)/, "$1");
or this for numbers:
inputField.value.replace(/(\.[0-9][0-9])([0-9])/, "$1");
I found this method here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Example:_Switching_words_in_a_string
<input type="text" id="decCheck" onkeyup="decimalCheck();"/>
<script>
function decimalCheck(){
var dec = document.getElementById('decCheck').value;
if(dec.includes(".")){
var res = dec.substring(dec.indexOf(".")+1);
var kl = res.split("");
if(kl.length > 1){
document.getElementById('decCheck').value=(parseInt(dec * 100) /
100).toFixed(2);
}
}
}
</script>
A similar solution with a backspace hit on reaching more than 2 decimal places.
function limitDec(id) {
// find elements
var amt = $("#testdec")
// handle keyup
amt.on("keyup", function() {
if (isNaN(amt.val())) {
amt.val(0);
}
if (amt.val().indexOf(".") > -1 && (amt.val().split('.')[1].length > 2)) {
amt.val(amt.val().substring(0, amt.val().length - 1));
}
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="text" id="testdec" onkeyup="limitDec(this.id)" />