I've got a system generated input field that expects it's value to be numeric & over 1,000.
This the HTML for the field
<input type="text" name="fr_goal" id="fr_goal" value="" size="15" maxlength="15">
I've got this JS running on it that gets me almost all the way there, BUT I can't actually tell if the value is greater or equal than the 1000 minimum value I require.
$('#fr_goal').on('keyup', function(evt) {
$("#fr_goal").removeClass('don-active');
var value = evt.target.value;
if (value.length === 0) {
evt.target.className = 'invalid-amount';
return;
}
else if ($.isNumeric(value) && value >= 1000) {
evt.target.className = 'valid-amount';
}
else {
evt.target.className = 'invalid-amount';
$(this).val('');
$(this).attr('placeholder', 'VIP goal must be greater than $1,000');
}
});
Now the else if is my desired outcome, ideally I know it's numeric and over 1000.
But what's happening is that as soon as I enter a number it defaults to my else case since the number is less than 1000.
Does anyone know of a way to listen in on that input once it's not "active" or in use to see what's been put inside it?
Ideally, I don't have to rely on a form submission to get the contents of the field and then present an error message. I'd like to be able to do it all "real-time"
Any help is much appreciated!
Thanks to Calvin for suggesting blur.
I kept everything from the original question almost exactly the same, just tweaked the else if to only look for numeric.
Once the input field is inactive this function runs, and solves my problem perfectly.
$('#fr_goal').blur(function(eval) {
var userInput = eval.target.value;
console.log("the inputted amount was" + userInput);
if (userInput >= 1000) {
eval.target.className = 'valid-amount';
}
else {
eval.target.className = 'invalid-amount';
$(this).val('');
$(this).attr('placeholder', 'VIP goal must be greater than $1,000');
}
});
Related
I am checking the validity of five unique inputs to prevent form submission when invalid inputs remain.
sE.addEventListener("input", (e) => {
if (
Number.isNaN(e.target.valueAsNumber) ||
sE.valueAsNumber >= Number(sE.max) ||
sE.valueAsNumber <= Number(sE.min)
) {
e.preventDefault();
calcButton.disabled = true;
} else {
calcButton.disabled = false;
}
This does appear to work to prevent the calculation button from being enabled, but only when the input (ie sE) is being looked at. This doesn't look at all the other inputs.
So I thought it would be better to try this:
sE.addEventListener("input", (e) => {
let reportS = sE.reportValidity();
let reportU = uE.reportValidity();
let reportV = vE.reportValidity();
let reportA = aE.reportValidity();
let reportT = tE.reportValidity();
console.log(reportS, reportU, reportV, reportA, reportT);
if (
Number.isNaN(e.target.valueAsNumber) ||
sE.valueAsNumber >= Number(sE.max) ||
sE.valueAsNumber <= Number(sE.min)
) {
e.preventDefault();
calcButton.disabled = true;
} else {
calcButton.disabled = false;
}
});
This gives me the appropriate true/false relationship between all five inputs. But, when you click on one of the inputs on the HTML form and enter a number, the cursor then jumps to the last selected input. This makes input impossible.
When I removed the let statements and put them outside of the function they do not call the correct true/false relationship as they aren't updated as each input has new data added. However, when the let statements are outside of the function, even though they do not accurately reflect the true/false relationship, the cursor does not jump from input to input.
I am very much a beginner so I am not sure what to look for when it comes to troubleshooting this strange phenomenon.
I made a JSBin for this https://jsbin.com/gowulec/edit?html,js,output
When you click all three checkboxes and then try to add data into the input.
I want to do JavaScript real time calculations oninput, without the need for a submit button.
I know how to do real time calculations in JavaScript when I have 1 input text field. I use the oninput event for the input text field.
But what about when I have 2 text fields?
I want it to do something like this link, where it validates and calculates without the need for a submit button:
https://www.easycalculation.com/algebra/modulo-calculator.php
Take the following code for example:
// input
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
// calculation
var result = a * b;
// display result
document.getElementById("result").value;
Since there are 2 input text fields (a and b), I want it to do the instant/real time calculations only AFTER the user has inputted valid data in BOTH text fields.
But I also want it to do real time calculations if the user changes either field. So if they input "a" and "b" it gives the results, but if they change "a" then it immediately gives new results without them having to touch "b" at all.
How do you suggest I go about doing this? Because I dont want the answer to keep showing up as Zero right after typing in the first text field. I want it to wait until both fields have numbers inputted and validated before it starts real time calculation. I will be adding validating code to this as well.
thanks
Just try and formulate your problem so that the computer can understand it.
I'll do just some pseudo-code. So you want to calculate something:
function calculate (valueA, valueB) {
... do something ...
... output result ...
}
You want to check, if both fields are valid, and only then do the calculation and output:
function checkFields (fieldA, fieldB) {
if (fieldA.value.length > 0) { // if it is empty, there is no input
... do some additional checking ...
if (fieldB.value.length > 0) { // if it is empty, there is no input
... do some additional checking ...
... if all went well: calculate (fieldA.value, fieldB.value);
}
}
}
then bind your checkFields to both input fields, and the computer understands.
you should write a function like validate() where you have to check the value of both the inpute fields if its valid then calculate result otherwise show a warning message above the field which is either empty or having wrong value
You have to call the validate function on onchange event of both the inputs
This is not exactly how I would write this in a production evvironment. but this should at least give you a good start for what you are looking for - very basic functionality you described.
<form>
<input id='a' class='ab' type='text' name='valA'>
<input id='b' class= 'ab' type='text' name='valB'>
</form>
// JS code below with this markup
var someCompositeGroup = document.getElementsByClassName("ab");
function validateForm(){
// add stuff here
var inputVal = 0;
var aVal = someCompositeGroup[0] && someCompositeGroup[0].value;
var bVal = someCompositeGroup[1] && someCompositeGroup[1].value;
if (aVal && bVal && !isNaN(aVal) && !isNaN(bVal)) {
inputVal = aVal * bVal;
// only update here -
console.log(inputVal);
} else {
console.log(' not ready to calculate yet ');
}
}
for (var i = 0; i < someCompositeGroup.length; i++) {
someCompositeGroup[i].addEventListener('keyup', validateForm);
}
I have an text input for pagination page changing. I need to limit typing of page numbers to some number f.e. 15 (max pages number). So i'm trying with this code below but always when number is higher than 15 value is changing to 15 and actual typing number.
actual.on('keypress', function() {
console.log('test');
var t = $(this);
if (t.val() < 1) t.val('1');
if (t.val() > 15) t.val('15');
});
Fiddle: http://jsfiddle.net/v6fhobr7/
Can anybody help?
Try changing it from 'keypress' to 'keyup' ... there's a slight flicker, but it works.
Use a number field.
<input type="number" min="1" max="15" step="1">
#rfornal's solution works okay, but it's hard to type single digit value unless you're really fast:
http://jsfiddle.net/v6fhobr7/7/
So it's better to set a slight timeout before changing the value:
var actual = $('.actual');
var tm;
actual.on('keyup', function () {
var t = $(this);
if (tm) clearTimeout(tm);
tm = setTimeout(function() {
if (t.val() < 1) t.val('1');
if (t.val() > 15) t.val('15');
}, 250);
});
JSFiddle demo: http://jsfiddle.net/v6fhobr7/10/
In jQuery 2.x, you can use actual.on('input'), which does what you want without the flicker.
Note that this will prevent the user from clearing out the input entirely; if you want to allow this then you might want to handle the case where t.val() == '' explicitly.
actual.on('input', function(e) {
var t = $(this);
if (t.val() == '') return;
if (t.val() < 1) t.val('1');
if (t.val() > 15) t.val('15');
});
http://jsfiddle.net/v6fhobr7/12/
Edit:
Note that this solution doesn't restrict input to only numeric characters (you can still type letters and symbols). If you want to prevent that, use this solution in addition to my answer above.
Or, if you don't care about IE 9 or mobile browsers, Mathletics's answer is the best.
I have a webpage where people enter information (name, job title, address, etc.) and it auto creates a business card for them. I currently have some jQuery that uses .change and looks at a field when a user changes it.
It looks for issues with what they enter, because some things must be in a certain format (ex- They enter the word "Avenue" and it won't let them add the item to their cart until they change it to Ave.)
I am trying to find some way to do this on the fly automatically with JS/jQuery, but I'm not sure what to do. What I would like is for the field to update itself, so if the user puts in "Avenue" it would auto update to "Ave." after the user tabs / exits the field.
Any idea on what JS and/or jQuery can be used to do this?
Here is my current code:
var x = "Clean";
var xD = " ";
$('#cartText4046').change(function () {
if ($(this).val().indexOf("Avenue") > -1) {
x = "Please use Ave. instead of Avenue.";
} else if ($(this).val().indexOf("avenue") > -1) {
x = "Please use Ave. instead of Avenue.";
... Additional rules here, omitted for space.
} else {
x = "Clean";
}
if (x != "Clean") {
$('#cartText4046').addClass("invalid");
xD = x;
} else if (x == "Clean") {
$('#cartText4046').removeClass("invalid");
xD = " ";
}
if (x != "Clean") {
$('.betabutton').html('<span id="addToBaskettext">To add this to the Basket,
please fix the following issue(s):<br><br> ' +xD'</span>');
$('.betabutton').addClass("invalidBtn");
} else if (x == "Clean") {
$('.betabutton').html('<a id="addToBasket" href="#" onclick="actionPageSubmit();return false;"><span id="addToBaskettext">Add to Basket</span></a>');
$('.betabutton').removeClass("invalidBtn");
}
Here is a working sample of what you may be looking for.
$("#textbox").on("change", function() {
$(this).val(function(index, value) {
return value.replace('Avenue', 'Ave.');
});
});
http://jsfiddle.net/decx8sw9/
If you really wanted it to do it after the user has finished making changes ("after the user tabs / exits the field.") you might want to bind to blur (fires when focus is lost/shifted to some other element)...
$('#cartText4046').on( "blur", function() {
$(this).val(function(index, value) {
value = value.replace('Avenue', 'Ave.');
// keep going ... value = value.replace('Street', 'St.') ..
return value;
});
EDIT: I reread the question, and now see that you wanted the correction to happen after the user exits the field. This answer provides inline autocorrection while the user types. I will leave it in case you find it useful after all.
You can lift the code from the jQuery Autocorrect Plugin: jsfiddle.
$("#textbox").autocorrect({
corrections: {
Avenue: "Ave.",
"...": "someWord"
}
});
My Requirement is to validate the ip ranges, I need to create a JavaScript function to accept only numeric and it must allow only between the range 0 to 255. If anything is entered beyond that it must alert a message.
I am currently using this below function
<script language="JavaScript">
function allownums(a)
{
if(a <48 ||a > 57)
alert("invalid")
else
alert("vaild")
}
</script>
<input type='text' id='numonly' onkeypress='allownums(event.keycode)'>
I am new to JavaScript, Need some experts suggestion to fix my requirement. Please suggest me
Thanks
Sudhir
Currently you have the test
(a < 48) || (a > 57)
for invalid values. So I would change those:
(a < 0 ) || (a > 255)
You may also need to consider what you'll do with non-integral input like 2.3 - either round it or treat it as invalid.
At present, as Kelvin Mackay points out, you are performing the validation on the keypress event rather than the input value, so change the onkeypress to allownums(this.value).
I would advise changing the alert to a warning in a div, and using the validation to enable/disable a submit button, as popups are quite annoying in just about every circumstance.
To clear the input when an invalid entry is made (as requested in a comment) would make it rather annoying for the user; as soon as a key is pressed to add a digit and make the input invalid, the whole input is cleared. The code, however, would be:
if(!validnum(this.value))
this.value="";
in the input tag, thus:
<input type='text' id='numonly'
onkeyup='if(!validnum(this.value)) this.value="";'>
with the function changed to:
function validnum(a) {
if(a < 0 || a > 255)
return false;
else
return true;
}
or more succinctly:
function validnum(a) {
return ((a >= 0) && (a <= 255));
}
Edit: To alert and clear the box, if you must:
function validOrPunchTheUser(inputElement) {
if(!validnum(inputElement.value)) {
window.alert('badness'); // punch the user
inputElement.value = ""; // take away their things
}
}
<input type='text' id='numonly'
onkeyup='validOrPunchTheUser(this)'>
However, reading other answers, apparently you are looking to validate an octet (e.g. in an IP address). If so, please state that in the question, as it passed me by today. For an octet:
function validateIPKeyPress(event) {
var key = event.keyCode;
var currentvalue = event.target.value;
if(key < 96 || key > 105)
{
event.preventDefault();
window.alert('pain');
return false;
}
else if(currentvalue.length > 2 ||
(currentvalue.length == 2 &&
key > 101)) {
window.alert('of death');
event.preventDefault();
event.target.value = event.target.value.substring(0,2);
}
else
return true;
}
With the input tag:
<input type='text' id='octet'
onkeydown='validateIPKeyPress(event)'>
Except please don't use alerts. If you take out the alert lines, it will silently prevent invalid inputs. Note the change to use onkeydown now, so that we can catch invalid key presses and prevent the value changing at all. If you must clear the input, then do if(!validateIPKeyPress(event)) this.value = "";.
I would rather go instantly for validation of whole ip address. Allowing input both numbers and dots, parsing them thru REGEX pattern.
Pattern usage example you could fetch here:
http://www.darian-brown.com/validate-ip-addresses-javascript-and-php-example/
The code itself would look something like:
<input type='text' id='numonly' value="" onkeypress='allowIp(event)' onkeyup='javascript:checkIp()'>
function allowIp(e){
if((e.keyCode < 48 || e.keyCode > 57) && e.keyCode != 46) // both nubmer range and period allowed, otherwise prevent.
{
e.preventDefault();
}
}
function checkIp()
{
var ip = $("#numonly").val();
/* The regular expression pattern */
var pattern = new RegExp("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
/* use javascript's test() function to execute the regular expression and then store the result - which is either true or false */
var bValidIP = pattern.test(ip);
if(bValidIP){
// IP has ok pattern
$("#numonly").css("background", "green");
}
else {
$("#numonly").css("background", "red");
}
}
You could check it here on fiddle
http://jsfiddle.net/Indias/P3Uwg/
Single Integer
You can use the following solution to check if the user input for a single integer is between 0 - 255:
document.getElementById('example').addEventListener('input', event => {
const input = event.target.value;
console.log(/^\d+$/.test(input) && input > -1 && input < 256);
});
<input id="example" type="text" placeholder="Enter single integer" />
IP Address
Alternatively, you can use the code below to verify that each section of an IP address is between 0 - 255:
document.getElementById('example').addEventListener('input', event => {
const input = event.target.value;
console.log(input === new Uint8ClampedArray(input.split('.')).join('.'));
});
<input id="example" type="text" placeholder="Enter IP address" />
You need to validate the current value of the input, rather than the last key that was pressed:
<input type='text' id='numonly' onkeypress='allownums(this.value)'>
Your function then just needs to be modified to: if(a < 0 || a > 255)
A function like this should do it:
function allownums(value){
var num = parseInt(value,10);
if(num <0 || num>255)
alert('invalid')
}
Then have your html look like:
<input type='text' id='numonly' onblur='allownums(this.value)'>
Live example: http://jsfiddle.net/USL3E/
Update
I've set up a fiddle that does some basic IP-formatting and checks weather or not all input is in range (0 - 255) etc... feel free to use it, improve it, study it... I've also updated the code snippet here to match the fiddle
There are several things you're not taking into account. First and foremost is that not all browsers have a keycode property set on the event objects. You're better off passing the entire event object to the function, and deal with X-browser issues there. Secondly, you're checking key after key, but at no point are you checking the actual value that your input field is getting. There are a few more things, like the use of the onkeypress html attribute (which I don't really like to see used), and the undefined return value, but that would take us a little too far... here's what I suggest - HTML:
<input type='text' id='numonly' onkeypress='allowNums(event)'>
JS:
function allowNums(e)
{
var key = e.keycode || e.which;//X-browser
var allow = '.0123456789';//string the allowed chars:
var matches,element = e.target || e.srcElement;
if (String.fromCharCode(key).length === 0)
{
return e;
}
if (allow.indexOf(String.fromCharCode(key)) === 0)
{//dot
element.value = element.value.replace(/[0-9]+$/,function(group)
{
return ('000' + group).substr(-3);
});
return e;
}
if (allow.indexOf(String.fromCharCode(key)) > -1)
{
matches = (element.value.replace(/\./g) + String.fromCharCode(key)).match(/[0-9]{1,3}/g);
if (+(matches[matches.length -1]) <= 255)
{
element.value = matches.join('.');
}
}
e.returnValue = false;
e.cancelBubble = true;
if (e.preventDefault)
{
e.preventDefault();
e.stopPropagation();
}
}
Now this code still needs a lot of work, this is just to get you going, and hopefully encourage you to look into the event object, how JS event handlers work and all the rest. BTW, since you're new to JS, this site is worth a bookmark
function fun_key()
{
var key=event.keyCode;
if(key>=48 && key<=57)
{
return true;
}
else
{
return false;
alert("please enter only number");
}
}
and you can call this function on keypress event like:
<asp:textbox id="txtphonenumber" runat="server" onkeypress="return fun_key()"> </asp"textbox>
I've seen many answers that have overlooked two important factors that may fail to validate range number on 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 255 is selected, pressing 9 will not turn into 2559 but 9 instead.
So first of all, write a simple function that check if the input value is selected by the user:
function isTextSelected (input) {
if (!input instanceof HTMLInputElement) {
throw new Error("Invalid argument type: 'input'. Object type must be HTMLInputElement.");
};
return document.getSelection().toString() != "" && input === document.activeElement;
}
Next, this will be your on keypress event handler that takes into consideration of the above two factors:
$("input[type='number']").on("keypress", function (e) {
if (!Number.isInteger(parseInt(e.key)) || (($(this).val() * 10) + parseInt(e.key) > 255
&& !isTextSelected($(this)[0]))) {
e.preventDefault();
};
});
Take note of this condition within another brackets, it is one whole condition by itself:
(($(this).val() * 10) + parseInt(e.key) > 255 && !isTextSelected($(this)[0]))
For the < 0 condition, you don't even need it here because the negative sign (-) will be automatically prevented as the sign itself is not an integer.
KNOWN ISSUE: The above solution, however, does not solve the situation when the user move the cursor to the start position of 29 and press 1, which will become 129. This is because 29 * 10 = 290, which already exceed 255, preventing user from entering 129, which is valid. The start position is particularly hard to track when the input type="number". But it should be enough to resolve the normal way of input for an integer range field. Any other better solutions are welcome.