Instant validation with optional function for number calculation with instant result - javascript

I want to show the error instantly until the request is filled right. It means that I want the user to get the number he is typing instantly without clicking the button...
Here is my code (also found on JSFiddle):
HTML:
<input type="number" id="myNumber" value="Error">
<button onclick="myFunction()">Click</button>
<p id="Error"></p>
JS:
window.myFunction = function() {
var err = " is not 1000!"
var num = document.getElementById("myNumber").value;
if (num == 1000) {
alert("No Errors!");
} else {
if (num !='') {
document.getElementById("Error").innerHTML = num+err;
}
else {
document.getElementById("Error").innerHTML = err;
}
}
}
I'm looking for a simple solution to use a function inside until the number is calculated, so to just show the "is not 1000" while typing something other than 1000 (like 1, 100, 1001 110011 etc..) can also be fine..

$("#myNumber").on("input",myFunction);
Dont wait for a click, but for an input. The upper is in jquery, pure js:
document
.getElementById("myNumber")
.addEventListener("input",myFunction);
or inline:
oninput="myFunction()"

you can call myFunction() on keyup event for your input box.
window.myFunction = function() {
var err = " is not 1000!"
var num = document.getElementById("myNumber").value;
if (num == 1000) {
alert("No Errors!");
document.getElementById("Error").innerHTML = "";
} else {
if (num !='') {
document.getElementById("Error").innerHTML = num+err;
}
else {
document.getElementById("Error").innerHTML = err;
}
}
}
<input type="number" id="myNumber" onkeyup="myFunction()" value="Error">
<button onclick="myFunction()">Click</button>
<p id="Error"></p>

Related

how to read multiple value length in javascript?

I am working on a barcode scanner and currently have a problem where I need the barcode to read 2 different value lengths, currently I have it set to submit the value at 9 length.
<span>
<input type="text" id="IC-input" name="IC" onkeyup="autofill(this.value)" placeholder="Enter your IC Number" required maxlength="12">
<label><button type="button" id="theButton" onclick="theButtonIsPressed()">Submit</button></label>
</span>
function autofill(value){
console.log("Autofill:"+value)
//console.log(9 digits);
button = document.getElementById("theButton");
if(value.length == 9){
console.log('form is ready to submit');
theButtonIsPressed(value);
}
}
now i need it to read from 12 value as well but it auto submits when the value hits 9 digits. I have tried OR function .
function autofill(value){
console.log("Autofill:"+value)
//console.log(9 digits);
button = document.getElementById("theButton");
if(value.length == 12 || value.length == 9){
console.log('form is ready to submit');
theButtonIsPressed(value);
}
}
i also tried the Else function
function autofill(value){
console.log("Autofill:"+value)
//console.log(9 digits);
button = document.getElementById("theButton");
if(value.length == 12){
console.log('form is ready to submit');
theButtonIsPressed(value);
}
else if(value.length == 9){
theButtonIsPressed(value);
}
}
But it would always read the first 9 value and leave the 3 other value unread. Does anyone have a solution for this? Thank you in advance.
Seems like you are listening to the keypress. Use a timer to cancel it. Basic idea of a debounce method.
var timer;
function autofill(value){
if (timer) window.clearTimeout(timer);
if(value.length === 9){
timer = window.setTimeout( function () {
processIt(value);
}, 50);
} else if(value.length === 12){
processIt(value);
}
}
function processIt(value){
console.log('here', value);
}
BUT That is a bad solution. Typically you set up the scanner to fire a tab or enter press so you know it is done. I would check to see if that is happening and listen for that instead. You can then just listen for that and you know the scanner is done.
var inp = document.getElementById("barcode");
inp.addEventListener("keydown", function (evt) {
if (["Tab", "Enter"].includes(evt.key)) {
evt.preventDefault();
console.log('scanner is done', evt.target.value);
}
});
<input type="text" id="barcode" />
The problem is that the autofill function runs to press the button as soon as the input box has 9 characters. It is because you are running the autofill function by the 'onkeyup' event listener attached to the input tag.
The solution is to run the autofill function after making sure there is a full length value intended. Good luck.
For a most common scene, the scanner will trigger such event one by one: focus, input character....input final 'Enter' character, so you have to take attention to the last event.
<script type="text/javascript">
window.addEventListener("load", function () {
var ic = document.getElementById("IC-input");
ic.addEventListener("focus", function (args) {
ic.value = "";
});
ic.addEventListener("keyup", function (args) {
if (args.key == "Enter") {
autofill(ic.value);
}
});
});
function autofill(value) {
console.log("Autofill:" + value)
//console.log(9 digits);
button = document.getElementById("theButton");
if (value.length == 9) {
console.log('form is ready to submit');
theButtonIsPressed(value);
}
}
</script>
<span>
<input type="text" id="IC-input" name="IC" onkeyup="input_keyup" placeholder="Enter your IC Number" required maxlength="12">
<label><button type="button" id="theButton" onclick="theButtonIsPressed()">Submit</button></label>
</span>

Form validation error message is overriding in javascript (only )

Hope, you all doing well.
I am trying to validate firstname input field of a form with Javascript. For some reason, error messages doesn't display in order. Some of them override others, only just one error message is displaying, the rest is not.
I'm wondering why? Can anyone shed me some light please?
Here is my code:
// Predefined validator function to check if input is empty or not
var validator = {};
validator.isEmpty = function(input) {
// Stop execution if input isn't string
if (typeof input !== 'string') return false;
if (input.length !== 0) {
for (var i = 0; i < input.length; i++) {
if (input[i] !== " ") {
return false;
}
return true;
}
}
return true;
};
validator.isEmpty(null); // returns false
// Main part to get inputs and apply validation
window.onload = function() {
var signUp = document.getElementById("signUp");
var fName = document.getElementById("fName");
var suButton = document.getElementById("subMit");
// Submit button on the function
suButton.addEventListener('click', function(event) {
isNameValid(fName);
});
signUp.addEventListener('submit', function(event) {
event.preventDefault();
});
function isNameValid(char) {
var val = char.value;
if (validator.isEmpty(val)) {
if (val.length < 2) {
// Display a message if input length is less than 2
char.setCustomValidity("We expect your input should contain at least 2 characters, darling !");
char.style.borderColor = "red";
}
if(!isNaN(val)) {
char.setCustomValidity("Please, enter only characters");
char.style.borderColor = "red";
}
} else {
char.setCustomValidity("");
char.style.borderColor = "green";
}
}
<form id="signUp">
<input type="text" id="fName" name="firstname" placeholder="First name">
<input type="checkbox" name="result" required autofocus> Agree our conditions
<input type="submit" id='subMit' value="SUBMIT">
</form>
It took me a while but I hope following works for you. Let me know if you need help understanding anything. I felt your code was a bit complex so I simplified it.
<script>
function submitForm(){
var formValid = false;
var msg = "";
var fNameElement = document.getElementById("fName");
if(fNameElement){
var fNameValue = fNameElement.value;
if(fNameValue.length < 2){
msg = "We expect your input should contain at least 2 characters, darling !";
}
else if(!(/^[a-zA-Z]+$/.test(fNameValue))){
msg = "Please, enter only characters";
}
else{
formValid = true;
}
if(formValid){
fNameElement.style.borderColor="green";
//do something
}
else{
fNameElement.style.borderColor="red";
alert(msg); // or show it in a div
}
}
}
</script>
<form id="signUp" action="javascript:submitForm()">
<input type="text" id="fName" name="firstname" placeholder="First name">
<input type="checkbox" name="result" required autofocus> Agree our conditions
<input type="submit" id='subMit' value="SUBMIT">
</form>
Fiddle: https://jsfiddle.net/fxumcL3d/3/

How to check if textbox value is not number?

<!DOCTYPE html>
<html>
<body>
<div id="text" class="CommentBox">
Some text :
<input type="text" />
</div>
<script>
$(document).ready(function () {
jQuery("#text").on("change", function () {
var x = $('#text').value;
if (isNaN(x))
{
window.alert("You have entered not a number");
return false;
});
});
});
</script>
</body>
</html>
I am trying to write javascript code to check if the given value is not number.If not i would like to give error message? If it is number I would like to check if it is integer and between 0 and 100.
Basically you need to convert to an Int before compare it with NaN which means something like:
var x = $('#text').value;
if ( isNaN( parseInt(x) ) ) {
// Not a decimal number.
}
There are a lot of syntax errors in your code.
Your selector checks your div for the change event instead of your input, which means it will never trigger the code.
You should use .val() to get the value of an element when using jQuery selectors instead of .value.
You can also use the this keyword inside the event handler to get the referenced element.
Besides that there were some misplaced ) and } in your code.
Below I have included an working sample of your code.
$(document).ready(function() {
jQuery("#text > input").on("change", function() {
var x = $(this).val();
if (isNaN(x)) {
window.alert("You have entered not a number");
return false;
} else if (x > 0 && x < 100) {
alert("number in between 0 and 100");
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text" class="CommentBox">
Some text :
<input type="text" />
</div>
function numberOrNot(var input)
{
try
{
Integer.parseInt(input);
}
catch(NumberFormatException ex)
{
return false;
}
return true;
}
this will return true if your input is number, otherwise it will return false
try this code
you enter direct input on change or write id for input and pass it to javascript
$(document).ready(function() {
jQuery("input").on("change", function() {
var x = $('#text').val();
if (isNaN(x)) {
window.alert("You have entered not a number");
return false;
}
else{
if(x>=0 && x<=100)
{
window.alert("You have enter write number");
}else{
window.alert("You enter number between 0 to 100");
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="CommentBox">
Some text :
<input type="text" id="text" />
</div>
You can use try-catch and put as many conditions you want in try block Like this. I have put three conditions for now.
<script type="text/javascript">
function Validation(){
var number1=document.LoginForm.number1.value;
try{
if(number1==""){
throw "Empty";
}
if(isNaN(number1)){
throw "Not a Number";
}
if(number1<0 || number1>100){
throw "Out of range";
}
}
catch(err){
if (err=="Empty"){
alert("Number 1 and Number 2 fields cannot be empty");
}
if (err=="Not a Number"){
alert("Please enter a number");
}
if(err=="Out of Range"){
alert("Out of Range");
}
return false;
}
//return true;
}
</script>

If condition not working in form validation

This is a question from my elder brother's question paper which I'm trying to solve but I am not able to do so .
Create a form containing a two Text fields and radio button and submit button. Name the
text fields account number and amount and radio button as transaction (deposit ,withdraw
and enquiry).Write a JavaScript the validates the text field to have only numbers, the first
text field should be of size 10 and second text field should have values between 500 to
20,000. Using onclick event a jQuery is called that performs necessary transactions and
display the updated value.
.............................................................................
So I have written the following code:
form1.html
<!DOCTYPE html>
<html>
<head>
<title>Web Tech DA 1</title>
<script type="text/javascript" src="script1.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#sub').click(function() {
var acc=document.getElementById("acc").value;
var amt=document.getElementById("amt").value;
var bal=acc%100;//balance , I am using this to dynamically generate a new balance each time a new account number is entered
$("#t1").click(function(){
bal=acc+amt;
alert(bal);
});
$("#t2").click(function(){
if(acc>amt){
bal=acc-amt;
alert(bal);
}
else{
alert('Insufficient Funds.');
}
});
$("#t3").click(function(){
alert(bal);
});
});
});
</script>
</head>
<body>
<form name="myform" onsubmit="if(validateform()) {window.alert('succefully submitted')} else {return false;}" >
<p>Account Number : <input type="text" maxlength="10" name="acc" id="acc" height="20px" width="100px" required="required" onblur="validacc(this.value)"></p>
<p>Amount : <input type="text" name="amt" id="amt" height="20px" width="100px" required="required" onblur="validamt(this.value)"></p>
<p>Transaction : <input type="radio" name="trans" id="t1" value="deposit" />Deposit
<input type="radio" name="trans" id="t2" value="withdraw" />Withdraw
<input type="radio" name="trans" id="t3" value="enquiry" />Enquiry </p>
<input type="submit" name="sub" id="sub" value="Submit">
</form>
</body>
main1.css
*{
margin:0;
padding: 0;
}
body{
margin: 25px;
}
form p {
margin: 10px;
}
form input {
margin: 10px;
}
script1.js
function validateform() {
var acc = document.getElementById("acc").value.trim();
var amt = document.getElementById("amt").value.trim();
if(validregno(acc)&&validname(amt))
{window.alert("No errors found");return true;}
else
{window.alert("invalid entries found");return false;}
}
// Overall Go
function validacc(r)
{
var p = new RegExp(/^[0-9]{10}$/i);
if(!p.test(r))
{
chngborder("acc");
return false;
}
chngborderr("acc");
return true;
}
function validamt(amt)
{
var p = new RegExp( /^[0-9]{1,}$/);
if(amt>=500 && amt<=20000){
if(p.test(n))
{
chngborderr("amt");
return false;
}
else
{
chngborder("amt");
return true;
}
}
chngborder("amt");
return false;
}
function chngborder(i)
{
document.getElementById(i).style.borderColor="red";
}//red color means wrong format
function chngborderr(i)
{
document.getElementById(i).style.borderColor="green";
}//green color means correct format
For some reason I'm not able to enter a number in the "Amount" text field and none of the radio buttons are working .
Please point out any mistakes that I have done here .
P.S. I'm new to jQuery and form validation
UPDATE
I made the changes pointed out and even then for some reason the "Amount" text field doesn't get validated and the "submit" button resets the form .
I am analysing your code. if this is exactly what you have, I can notice that
1 - You did not include jQuery library in the of you.
you can do it by adding <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> or <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script> inside the <head> element
2 - I think it is better to add and Else in onsubmit event of #myForm
if(validateform()) window.alert('succefully submitted'); else return false.
3 - I have never seen a javascript (.js files) variable declaration starting by int: they start with var keyword regardless the type of the variable
Here is a working code.
script1.js
function validateform() {
var accValue = document.getElementById("acc").value.trim();
var amtValue = document.getElementById("amt").value.trim();
if (validacc(accValue) && validamt(amtValue))
{ window.alert("No errors found"); return true; }
else
{ window.alert("invalid entries found"); return false; }
}
// Overall Go
function validacc(r) {
var p = new RegExp(/^[0-9]{10}$/i);
if (!p.test(r)) {
chngborder("acc");
return false;
}
chngborderr("acc");
return true;
}
function validamt(amt) {
var p = new RegExp(/^[0-9]{1,}$/);
var amtValue = document.getElementById("amt").value;
if (amtValue >= 500 && amtValue <= 20000) {
if (p.test(n)) {
chngborderr("amt");
return false;
}
else {
chngborder("amt");
return true;
}
}
chngborder("amt");
return false;
}
function chngborder(i) {
document.getElementById(i).style.borderColor = "red";
}//red color means wrong format
function chngborderr(i) {
document.getElementById(i).style.borderColor = "green";
}
//Script inside your html file
$(document).ready(function () {
$('#sub').click(function() {
var accValue = document.getElementById("acc").value;
var amtValue = document.getElementById("amt").value;
var bal = accd % 100;})
$("#t1").click(function(){
bal = Number(document.getElementById("aac").value) +
Number(document.getElementById("amt").value);
alert(bal);
});
$("#t2").click(function(){
if(acc > amt){
Number(document.getElementById("aac").value) +
Number(document.getElementById("amt").value);
alert(bal);
}
else{
alert('Insufficient Funds.');
}
});
});

Jquery / window.onbeforeload in custom jquery function

I want to add to this code a "window.onbeforeload" event to show a message that prevent the user from quitting the current page without adding the products to cart.
I have to show only when the quantity in > than 0 and with respecting the code below.
How can I do that ?
<form> <p><input class="qty"
type="text" maxlength="1" value="0" /></p>
<p><input class="qty" name="text"
type="text" value="0" /></p> <p><input
class="qty" name="text2" type="text"
/></p> </form>
<script type="text/javascript">
$(".qty").change(function(e) {
if(this.value != '3' && this.value != '6' && this.value != '9') {
this.value = 0;
alert('You can buy only 3, 6, or 9 pieces fromn this product');
} }); </script>
Thanks for help :)
Not sure why everyone is suggesting globals. This method requires no globals and no change() listener (which you may still need if you want that alert there). Based on MDC, assuming support for [].indexOf:
window.onbeforeunload = function (e) {
var e = e || window.event;
if (['3','6','9'].indexOf($(".qty").val())>=0) {
return;
}
else {
var msg = 'You can buy only 3, 6, or 9 pieces from this product';
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = msg;
}
// For Safari
return msg;
}
};
With multiple inputs you will need to change the condition slightly:
var valid = true;
$('.qty').each(function(){ valid = valid && ['3','6','9'].indexOf($(this).val())>=0; });
if (valid) {
return;
}
else { ... }
You would need to set some "global" variable. GLobal does not necessarily mean global to the window, just enough it's global in your own namespace (which you hopefully got).
if(this.value != '3' && this.value != '6' && this.value != '9') {
NotifyTheUser = true;
}
else {
NotifyTheUser = false;
}
window.onbeforeunload = function() {
if( NotifyTheUser ) {
return 'Check your input.. foo bar yay!';
}
};
you can save the value in some global variable and then onbeforeunload look for that value, whether it's greater than 0 or not.
var valueContainer = 0;
$(".qty").change(function(e) {
valueContainer = this.value;
//rest of your code
});
window.onbeforeunload = function() {
if( valueContainer == 0) {
return 'Please Don't go away without selecting any product :(';
} };

Categories