I'm coding a Simple Dependable Logic
I have a DropDown list called "frequencyList"
which contains values like -
"Hourly", "Daily", "Weekly", "Monthly"
I have Textbox called "frequencyCount"
which must accept only Digits.
Now the Logic I need is -
If user selects "Hourly" option from the DropDown
The TextBox must only accept integer values between 1-23 else throw error,
If user selects "Daily", TextBox to accept only between 1-30, and so on
So here is my flawed logic so far, please correct me -
$("#frequencyCount").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))
{
console.log("Invalid Input, It's not Digits");
}
else
{
//Input is Digits for sure now
if (frequecyList == "Daily")
{
if (frequencyCount >= 1 && frequencyCount <= 30)
{
console.log("Valid Daily input");
}
else
{
console.log("Invalid frequency");
}
}
}
});
Try this, it will help you
function validate() {
var freq = $("#frequency").val();
var num = $("#fvalue").val();
var error = 0;
if(freq==1 && (num <1 || num >23) ) {
error = 1;
}
else if(freq==2 && (num <1 || num > 30) ) {
error = 1;
}
if(error==1)
{
alert("error");
$("#fvalue").val('');
$("#fvalue").focus();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="frequency">
<option value="1">Hourly</option>
<option value="2">Daily</option>
<option value="3">Weekly</option>
<option value="4">Monthly</option>
</select>
<input type="number" id="fvalue" onblur="validate();" />
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.
I got a situation in which, I am validating input type using jquery.
I have html drop down list which contains different parameters("select:first-child").
I am trying validating input box based on these parameters for this I have written following code in jquery.
For example-
If I select "Quantity" then input box should take only numbers.
If I select "TradeDate" then input box should take date.
Now problem is ,when I select parameter which has type date , datepicker appears to select date.
But when I select any other parameter having type numbers ,input still showing datepicker.
So, Where I am wrong ,I want each time this validation
Here var type[1] contains type of parameter eg. float,date,char etc.
$("#cond_div").children("select:first-child").change(function(event){
var temp = $(this).val();
var type = temp.split("_");
$("#cond_div").children("input").on("keypress keyup", function () {
if (type[1].localeCompare("date") == 0) {
$(this).datepicker();
}
else if (type[1].localeCompare("float") == 0) {
$(this).val($(this).val().replace(/[^0-9\.]/g, ''));
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
}
else if (type[1].localeCompare("int") == 0) {
$(this).val($(this).val().replace(/[^0-9\.]/g, ''));
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
}
});
});
Once you've transformed an input with the .datepicker() creator, it stays that way until you destroy it by calling .datepicker("destroy") function.
SOLVED...
Instead of going with tricky logic ,found a simple way
$(document).ready(function () {
$("#cond_div").children("select:first-child").change(function (event) {
var temp = $(this).val();
var type = temp.split("_");
console.log("->" + temp);
console.log("->" + type);
$("#cond_div").children("input").val("");
$("#cond_div").children("input").datepicker("destroy");
if (type[1].localeCompare("date") === 0) {
console.log(type[1]);
$("#cond_div").children("input").datepicker();
} else if (type[1].localeCompare("char") === 0) {
console.log(type[1]);
$("#cond_div").children("input").attr("type", "text");
} else if (type[1].localeCompare("float") === 0) {
console.log(type[1]);
$("#cond_div").children("input").attr("type", "number");
} else if (type[1].localeCompare("int") === 0) {
console.log(type[1]);
$("#cond_div").children("input").attr("type", "number");
}
});
});
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">
Hi all I have written a script to allow only decimal in textbox
function onlyDecimal(evt) {
if (!(evt.keyCode == 46 || (evt.keyCode >= 48 && evt.keyCode <= 57)))
return false;
var parts = evt.srcElement.value.split('.');
if (parts.length > 2)
return false;
if (evt.keyCode == 46)
return (parts.length == 1);
if (parts[0].length >= 15)
return false;
if (parts[1].length >= 3)
return false;
}
<asp:TextBox ID="txtDecimal" runat="server" OnKeyPress="return onlyDecimal(event)" />
This is only allowing the following inputs
1.000
12.000
123.123
But I would like to restrict the following after decimal only 3 digits before decimal it can accept up to 15 digits so can some one help me like the following 1234.123,12345.123 and so on
Also If I enter 12.123 and trying to edit the decimal part it is not allowing me to edit the value until I clear that value
You can add "FilterNumber" class in the textbox and implement jquery to achieve your functionality
<asp:TextBox ID="txtDecimal" CssClass="FilterNumber" runat="server" />
$(".FilterNumber").live("keypress", function (e) {
var caretPosition = doGetCaretPosition(this);
var code = (code ? code : e.which);
//if it is delete,navigation keys always allow
if (code == 0 || code == 8)
return true;
var Value = $(this).val();
if (Value.indexOf('.') != -1) {
var splt = Value.split('.');
var indexofDot = Value.indexOf('.');
if (caretPosition > indexofDot) {
//allow only three character after .
if (splt[1].length > 2) {
return false;
}
}
else {
//allow only fifteen character before .
if (splt[0].length > 14) {
return false;
}
}
}
if (code != 46 && code > 31 && (code < 48 || code > 57))
return false;
//if it is (.)
else if (code == 46) {
var Value = $(this).val();
//if value already contains (.) character
if (Value.indexOf('.') != -1) {
var splt = Value.split('.');
//if there is already(.) char then return false
if (splt.length >= 2)
return false;
}
}
return true;
});
You need the caret position on the textbox so that you can know whether the use is entering the numbers before . or after .
function doGetCaretPosition(oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange();
// Move selection start to 0 position
oSel.moveStart('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionStart;
// Return results
return (iCaretPos);
}
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)" />