Is there a solution to "Invalid Value"? - javascript

It seems like I can't find why it shows EVERYTIME I type in something. It's supposed to only shows when user types in letter or negative numbers. Does it have something to do with "else"?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Examus</title>
</head>
<body>
<h1 id="label"></h1>
<input type="text" id="input">
<button onclick="checkAge()">Check Age</button>
<script>
const checkAge = () => {
const input = document.getElementById("input");
const inputValue = parseInt(input.value);
let output;
if (Number.isInteger(inputValue) || inputValue < 0) {
output = "Invalid Value";
document.getElementById("label").innerText = output;
return;
}
if (inputValue < 14 && inputValue > 0) {
output = "This person is a KID";
} else if (inputValue > 14 && inputValue < 18) {
output = "This person is a TEEN";
} else if (inputValue > 18 && inputValue < 60) {
output = "This person is a ADULT";
} else if (inputValue > 60) {
output = "This person is a SENIOR";
} else {
output = "Invalid Value";
}
document.getElementById("label").innerText = output;
}
</script>
</body>
</html>

I bet you wanted to say: If it is not a number or it is less than zero here:
if( Number.isInteger(inputValue) || inputValue < 0 ) {
So you need to add boolean inversion before call to Number.isInteger:
if( ! Number.isInteger(inputValue) || inputValue < 0 ) {
Also, you will need to use the operator "less or equal" (<=) or "greater or equal" (>=), so your condition will include ages 14, 18 and 60:
if (!Number.isInteger(inputValue)) {
document.getElementById("label").innerText = "Invalid Value";
return;
}
if (inputValue >= 0 && inputValue < 14) {
output = "This person is a KID";
} else if (inputValue >= 14 && inputValue < 18) {
output = "This person is a TEEN";
} else if (inputValue >= 18 && inputValue < 60) {
output = "This person is a ADULT";
} else if (inputValue >= 60) {
output = "This person is a SENIOR";
} else {
output = "Invalid Value";
}

Related

make an html and javascript to classified person based on their age

I want to do my JavaScript revision but I got stuck to this question. is there a simple code of html and JavaScript to achieve the answers to these question?
I have tried a simple look of html and JavaScript. but since I am a beginner. some words in this question I may find it hard.
<!DOCTYPE html>
<html>
<script src="js/age.js" language="javascript"></script>
<script>
function myFunction() {
var msg;
if (age == 0 && age <= 2) {
msg = "Toddler";
} else if (age == 3 && age <= 11) {
msg = "Child";
} else if (age == 12 && age <= 17) {
msg = "Adolescent";
} else {
msg = "Adult";
}
document.getElementById("demo").innerHTML = msg;
}
</script>
<body> Age: <input type="text"> <button onsubmit="return myFunction()">Find Category</button> </body>
</html>
less than or equal is <= - the => is called a fat arrow and used in the arrow function below
onclick is the event, but use an eventListener
You do not store the age from the input field
You do not have a demo element
Here is a better script. Please study it.
window.addEventListener("DOMContentLoaded", () => { // when the page has loaded
const findButton = document.getElementById("find");
const demo = document.getElementById("demo");
findButton.addEventListener("click", e => { // clicking the button
let msg;
let age = document.getElementById("age").value;
if (age >= 0 && age <= 2) {
msg = "Toddler";
} else if (age >= 3 && age <= 11) {
msg = "Child";
} else if (age >= 12 && age <= 17) {
msg = "Adolescent";
} else {
msg = "Adult";
}
demo.innerHTML = msg;
});
});
Age: <input type="text" id="age"> <button type="button" id="find">Find Category</button>
<span id="demo"></span>

How to fix credit card input spacing

I researched this on stack overflow, tried different answers but nothing worked for me. Can someone fix the problem please.
function spacingFunction() {
let varNumber = document.getElementById('cardnumber');
position = varNumber.selectionEnd;
varNumber.value = varNumber.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim()
varNumber.selectionEnd = position += ((varNumber.value.charAt(position - 1) === ' ' && varNumber.value.charAt(length - 1) === ' ' && length !== varNumber.value.length) ? 1 : 0);
}
<input id="cardnumber" placeholder="e.g. 1234 5678 9123 0000" maxlength="19" type="text" onkeydown="spacingFunction()">
I tried all fix examples from the site. Need solution
Your question was very unclear, but I believe that you asked to fix the spacing issue, here's a very good example on jsfiddle
input_credit_card = function(input)
{
var format_and_pos = function(char, backspace)
{
var start = 0;
var end = 0;
var pos = 0;
var separator = " ";
var value = input.value;
if (char !== false)
{
start = input.selectionStart;
end = input.selectionEnd;
if (backspace && start > 0) // handle backspace onkeydown
{
start--;
if (value[start] == separator)
{ start--; }
}
// To be able to replace the selection if there is one
value = value.substring(0, start) + char + value.substring(end);
pos = start + char.length; // caret position
}
var d = 0; // digit count
var dd = 0; // total
var gi = 0; // group index
var newV = "";
var groups = /^\D*3[47]/.test(value) ? // check for American Express
[4, 6, 5] : [4, 4, 4, 4];
for (var i = 0; i < value.length; i++)
{
if (/\D/.test(value[i]))
{
if (start > i)
{ pos--; }
}
else
{
if (d === groups[gi])
{
newV += separator;
d = 0;
gi++;
if (start >= i)
{ pos++; }
}
newV += value[i];
d++;
dd++;
}
if (d === groups[gi] && groups.length === gi + 1) // max length
{ break; }
}
input.value = newV;
if (char !== false)
{ input.setSelectionRange(pos, pos); }
};
input.addEventListener('keypress', function(e)
{
var code = e.charCode || e.keyCode || e.which;
// Check for tab and arrow keys (needed in Firefox)
if (code !== 9 && (code < 37 || code > 40) &&
// and CTRL+C / CTRL+V
!(e.ctrlKey && (code === 99 || code === 118)))
{
e.preventDefault();
var char = String.fromCharCode(code);
// if the character is non-digit
// OR
// if the value already contains 15/16 digits and there is no selection
// -> return false (the character is not inserted)
if (/\D/.test(char) || (this.selectionStart === this.selectionEnd &&
this.value.replace(/\D/g, '').length >=
(/^\D*3[47]/.test(this.value) ? 15 : 16))) // 15 digits if Amex
{
return false;
}
format_and_pos(char);
}
});
// backspace doesn't fire the keypress event
input.addEventListener('keydown', function(e)
{
if (e.keyCode === 8 || e.keyCode === 46) // backspace or delete
{
e.preventDefault();
format_and_pos('', this.selectionStart === this.selectionEnd);
}
});
input.addEventListener('paste', function()
{
// A timeout is needed to get the new value pasted
setTimeout(function(){ format_and_pos(''); }, 50);
});
input.addEventListener('blur', function()
{
// reformat onblur just in case (optional)
format_and_pos(this, false);
});
};
input_credit_card(document.getElementById('cardnumber'));
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input id="cardnumber" placeholder="e.g. 1234 5678 9123 0000" maxlength="19" type="text" onkeydown="spacingFunction()">
<script src="script.js"></script>
</body>
</html>

How to allow only Credit/Debit card number format in ASP.NET textbox

I have to allow only Debit/Credit card number format in asp.net textbox. Below is a sample screenshot-
Please let me know how to do this with asp.net textbox and I don't have to use validators.
Note: I only have to allow numbers and after every 4 numbers there
should be a hyphen(-).
I would strongly recommend you not to reinvent the bicycle and use jQuery inputmask plugin which will let you do the following:
$("input").inputmask({
mask: "9999 9999 9999 9999",
placeholder: ""
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jquery.inputmask.bundle.js"></script>
<input type="text"/>
Note that in this code I assumed that card number consists of 4 groups of 4 digits each, and it is not always true - it depends on expected cards' payment systems, country etc.
You can easily achieve any result by adding or removing digits in mask.
You can do the following:
<input type="text" onkeypress="return allowNumbersAndHyphen(event)">
function allowNumbersAndHyphen(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
//allowing numbers, left key(37) right key(39) backspace(8) delete(46) and hyphen(45)
var length = $('input').val().length;
if (((charCode == 37 || charCode == 39 || charCode == 8 || charCode == 46 || charCode == 45) || !(charCode > 31 && (charCode < 48 || charCode > 57))) && length <19)
{
return true;
}
else{
return false;
}
}
//put hyphens atomatically
$(document).ready(function(){
$('input').on('keypress', function() {
var temp = $(this).val();
if (temp.length == 4 || temp.length == 9 || temp.length == 14) {
$('input').val(temp + '-');
}
});
$('input').on('blur', function() {
var regex = /^[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}$/;
var cardNumber = $(this).val();
if(regex.test(cardNumber)) {
//success
alert('successful');
}
else {
//show your error
alert('Error');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- begin snippet: js hide: false console: true babel: false -->
Using vanilla javascript
document.getElementById('inp1').onkeypress = verify;
console.clear();
function isKeyValid(key) {
if(key > 47 && key < 58) return true
else if(key === 45) return true;
else return false;
}
function isValidCard(arr, isDash) {
const last = arr[arr.length - 1];
if(last.length === 4 && !isDash) return false;
else if(isDash && last.length !== 4) return false;
else if(isDash && arr.length === 4) return false;
else return true;
}
function verify(e) {
const key = e.keyCode || e.which;
const isDash = key === 45;
const val = e.target.value;
const input = val.split('-');
if (!isKeyValid(key) || !isValidCard(input, isDash)) {
return e.preventDefault();
}
// ...do something
}

unsure how to display results using getelementbyId // javascript

Ok so my code is below. Once the calculate price button is clicked, I want it to display the results beneath the button. ie. number of cars = CarNumber, type of car = CarType and the price of the car = CarPrice. I know this is probably super easy to do but I just cant get it to work.
HTML:
<!DOCTYPE html>
<html>
<body>
<form name="Cars">
<h1>Car Sales</h1>
<p>Which type of car would you like (A, B or C)</p>
<input type="text" name="CarType"><br>
<p>how many cars would you like (1-100)</p>
<input type="text" name="CarNumber"><br>
<br>
<button onclick="return beginfunction()">Calculate Price</button>
<p id="message"></p>
<script src="car.js"> </script>
</form>
</body>
</font>
JavaScript:
function beginfunction() {
var CarType = document.forms["Cars"]["CarType"].value;
var CarNumber = document.forms["Cars"]["CarNumber"].value;
var CarPrice;
if ( !( CarType == 'A' || CarType == 'B' || CarType == 'C' ) ) {
CarTypeError = "Invalid Car Type";
document.getElementById("message").innerHTML = CarTypeError;
return false;
}
{
if (isNaN(CarNumber)) {
CarNumberError = "Invalid Quantity Entered";
document.getElementById('message').innerHTML = CarNumberError;
return false;
}
}
{
if (CarNumber >0 && CarNumber <10)
{
}
else
CarError = "Invalid";
document.getElementById('message').innerHTML = CarError;
return false;
}
{
if (CarType == 'A') {
CarPrice = 30;
} else if (CarType == 'B') {
CarPrice = 20;
} else if (CarType == 'C'){
CarPrice = 10;
}
}
}
The way that you use innerHTML is right, but there is some logic problems in your function, here is the refactored code:
function beginfunction() {
var CarType = document.forms["Cars"]["CarType"].value;
var CarNumber = document.forms["Cars"]["CarNumber"].value;
var CarPrice;
var message = "";
if ( !( CarType == 'A' || CarType == 'B' || CarType == 'C' ) ) {
message = "Invalid Car Type";
}else{
if (CarType == 'A') {
CarPrice = 30;
} else if (CarType == 'B') {
CarPrice = 20;
} else if (CarType == 'C'){
CarPrice = 10;
}
message = CarPrice;
}
if (isNaN(CarNumber)) {
message = "Invalid Quantity Entered";
}
if (CarNumber >0 && CarNumber <10)
{
}
else{
message = "Invalid";
}
document.getElementById('message').innerHTML = message;
return false;
}

Allow to enter only 2 decimal points number

I have a condition to allow user to input only 2 decimal points number and restrict the alphabets and other characters. I used the following function:
function isNumberKeyOnlyWithDecimalFormat(event,value,id){
var val = value;
if (event.shiftKey === true) {
event.preventDefault();
}
if ((event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 96 && event.keyCode <= 105) ||
event.keyCode == 8 ||
event.keyCode == 9 ||
event.keyCode == 37 ||
event.keyCode == 39 ||
event.keyCode == 46 ||
event.keyCode == 190) {
} else {
event.preventDefault();
}
if(val.indexOf('.') !== -1 && event.keyCode == 190){
event.preventDefault();
}
if ((pointPos = $('#'+id).val().indexOf('.')) >= 0){
$('#'+id).attr("maxLength", pointPos+3);
}
else
$('#'+id).removeAttr("maxLength");
}
It is working fine while first time adding. But it restricts the if i want to edit the digits if it has already 2 decimal place. Can anyone help with this?
Try this. It will check the value each time the focus is gone from the input field, but you can use any event you like. It will parse the value as a float, and then round it to 2 decimal points.
Here is the fiddle: http://jsfiddle.net/sAp9D/
HTML:
<input type="text" id="the_id" />
JavaScript:
var input_field = document.getElementById('the_id');
input_field.addEventListener('change', function() {
var v = parseFloat(this.value);
if (isNaN(v)) {
this.value = '';
} else {
this.value = v.toFixed(2);
}
});
Your question is very hard to understand but if you want to check that a string has only 2 decimals then you can just do this
if( value.match(/\./g).length === 2 ) {
// Number has 2 decimals eg. 1.2.3
} else {
// Number is incorrect eg. 1.2.3.4
}
or if you want 1.2 then
if( value.match(/\./g).length === 1 ) {
// Code....
}
I use the following
// This function will only allow digits
function numericFormat( fld , e , extraStrCheck )
{
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
if ( extraStrCheck )
strCheck += extraStrCheck;
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;
if (whichCode == 13) return true; // Enter
if (whichCode == 8) return true; // Backspace
if (whichCode == 0) return true; // Null
if (whichCode == 9) return true; // Tab
key = String.fromCharCode(whichCode); // Get key value from key code
if ( strCheck.indexOf(key) == -1 ) return false; // Not a valid key
var x = new String(fld.value);
if ( key == '.' )
{
var exp = /\./;
var a = x.search(exp);
if ( a != -1 ) return false;
}
}
// samer code on change or on blur event
function allow2decimal(obj){
var v = parseFloat($(obj).val());
if (isNaN(v)) {
$(obj).value = '';
} else {
newVal = v.toFixed(2);
if(newVal >= 100){
$(obj).val( 100 );
}else{
$(obj).val(newVal);
}
}
}
//usage
<input
onkeypress="return numericFormat( this , event , '.');"
onchange="allow2decimal(this)"
value="0.1"
id="factory_silk" name="factory_silk" />
<html>
<head>
<script type="text/javascript">
function NumAndTwoDecimals(e, field) {
var val = field.value;
var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;
if (re.test(val)) {
}
else {
val = re1.exec(val);
if (val) {
field.value = val[0];
}
else {
field.value = "";
}
}
}
</script>
</head>
<body>
<input type="text" name="text" onkeyup="NumAndTwoDecimals(event , this);">
</body>
</html>
$('.number').keypress(function(evt){
var str = $(this).val();
var index = str.indexOf('.');
if(index==-1){index=0;}else{index= index+1;}
var extrapoint = str.indexOf('.',index);
if(extrapoint>0){$(this).val(str.slice(0,-1));}
var charCode = (evt.which) ? evt.which : event.keyCode;
if(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
var validNumber = new RegExp(/^\d*\.?\d*$/);
var lastValid = $(this).val();
if (validNumber.test($(this).val()))
{
lastValid = $(this).val();
}
else
{
$(this).val(lastValid);
}
});

Categories