Javascript if clause not working properly - javascript

I have the following Javascript/jQuery:
$('#List').keypress(function (e) {
if (e.which == 13) {
var lines = $('#List').val().split('\n');
mylast = lines[lines.length - 1];
mylen = mylast.length;
if ((mylen != 8) || (mylen != 4)) {
lines = lines.slice(lines.length-1);
$('#List').val(lines.join("\n"));
alert(mylen);
return false;
}
return true;
}
});
But it jumps into the code block after if even if length is 4 or 8....
Where is my error?
I want to remove the last line of the textarea if it's not of a given length.

It should not be:
if ((mylen != 8) || (mylen != 4)) {
it should be:
if ((mylen != 8) && (mylen != 4)) {
your way if it was 8 , it was not 4 so it was getting through or if it was 4 it was not 8. you need to check that its not either

This line:
if ((mylen != 8) || (mylen != 4)) {
means "if length is not 8 or length is not 4". So for instance, 4 is not 8, so the condition is true (the second part is never tested, because JavaScript expressions are short-circuited). Similarly, if it's 8, the first part of the expression is false, but the second part (8 != 4) is true, and so the expression is true.
You probably want:
if ((mylen != 8) && (mylen != 4)) {
&& means "and."

Lets examine the case of when mylen is 4.
mylen != 8 //true
mylen != 4 //false
true || false // true
What you probably want is to prevent mylen from being 8 and prevent mylen from being 4:
(mylen != 8) && (mylen != 4)

FWIW, here's a better version of your code:
$('#List').keypress(function (e) {
var lines, last, valid;
if (e.which === 13) {
lines = $(this).val().split('\n');
last = lines.pop();
valid = last.length === 4 || last.length === 8;
if (!valid) {
$(this).val(lines.join("\n"));
e.preventDefault();
}
}
});
it declares all variables as local (never forget the var keyword!)
it uses $(this) instead of repeating the $('#List')
it uses e.preventDefault() instead of returning false
it uses a variable named valid to transport meaning clearer
it uses strict comparison (===)
if the code is part of a form validity check, consider putting it into the submit event handler instead of capturing the Enter key.

Related

Improving if-else with multiple values?

Is there a better way to do this?
if(cpf.length !== 11 || cpf === "00000000000" || cpf === "11111111111" ||
cpf === "22222222222" || cpf === "33333333333" || cpf === "44444444444" ||
cpf === "55555555555" || cpf === "66666666666" || cpf === "77777777777" ||
cpf === "88888888888" || cpf === "99999999999"){
You could debate if this is better but this is what I like to do in that sort of situation:
// Name this something relevant to the problem
var possibleValues = ["0000000000", ...];
if (possibleValues.includes(cpf)) {
// do stuff
}
or if you're in an environment that doesn't have includes
if (possibleValues.indexOf(cpf) > -1) {
// do stuff
}
Another possibility is using a regular expression:
if (cpf.length === 11 && cpf.match(/^(\d)\1+$/)) {
// do stuff
}
^: Start at the beginning
(\d): Look for a digit and remember it
\1+: Look for the remembered digit repeatedly
$: Hit the end of the string
Using indexOf Something like
var possibleValues = [ "00000000000", "1111111111" ]; //add more values
if ( cpf.length != 11 || possibleValues.indexOf( cpf ) != -1 )
{
//value matching
}
Alternative Ecmascript5 solution using isNaN() and RegExp.text() functions:
if (cpf.length !== 11 || (!isNaN(f = cpf[0]) && new RegExp("^"+ f + "{11}$").test(cpf))) {
// do something
}
isNaN() - to check if we have only numbers(at start)
new RegExp("^"+ f + "{11}$").test(cpf) - to test if we have a sequence of same 11 digits

javascript to allow only negative and positive numbers and decimal upto 6 digits on keypress

I need to validate a textbox in my cshtml page to accept only negative or positive numbers and upto 6 decimal places. This is what I have tried so far.
function AcceptUptoSixDecimalPlacesWithNegative(event, elem) {
if ((event.which != 46 || $(elem).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
if (event.keyCode !== 8 && event.keyCode !== 46 && event.keyCode !== 9 && event.keyCode !== 0 && event.keyCode !== 45) { //exception
event.preventDefault();
}
}
var text = $(elem).val();
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 6)) {
if (event.keyCode !== 8 && event.keyCode !== 46 && event.keyCode !== 9) { //exception
event.preventDefault();
}
}
This is helping me achieve six digits after decimal point but then it allows all special characters and alphabets too.
Any help with this problem would be appreciated.
Thanks.
You could check the value with Regex:
var re = /^-?\d*\.?\d{0,6}$/;
var text = $(elem).val();
var isValid = (text.match(re) !== null);
The Regex means:
^ : beginning of string
-? : one or zero "-"
\d* : 0 to infinite numbers
\.? : 0 or 1 "."
\d{0,6} : from 0 to 6 numbers
$ : End of string
You could use the isNaN() function of JavaScript.
var inputPrevValue = "";
$(document).ready(function () {
$("#numbersOnly").change(function () {
if (isNaN($(this).val()) || $(this).val().length > 6) {
$(this).val(inputPrevValue);
} else {
inputPrevValue = $(this).val();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" id="numbersOnly">
This is a (very simplistic) example that tests if the input is a number less than 6 characters in length. If not, it'll revert it to the last acceptable value.
***Adding Comment as no access yet!!!
Try Regex "^[0-9]+(.[0-9]{1,2})?$" to verify the text and then proceed with logic.
js code:
var patt = new RegExp("^[0-9]+(.[0-9]{1,6})?$");
var res = patt.test(str);
if res is true then proceed else return false;
Here are a list of functions to help in your question:
Math.sign() checks if its a positive/0, negative/0 and NaN
Number MDN contains a list of number functions
parseFloat()
count digits after decimal post or regex ie. \d+([.\d{1,6}]*)\
In your context, a combination of validations in the following example:
let x = elem;
if(Math.sign(x) === 1 || Math.sign(x) === -1) && ...
// decimal validations
Hope this helps.
Don't validate the keys pressed. There are many ways to change input
value. Handle the oninput event.
You may treat the value as a string and validate using a
regular expression, but I think it's better to combine string and number-related
functions
For example:
<input type="number" step="any" oninput="validate(this)" />
function validate(input){
var number = parseFloat(input.value);
if( number == input.value && input.value.length <= number.toFixed(6).length ){ /* valid! */ }
}
http://jsfiddle.net/tto2yvwj/

jQuery function for check textbox

I’d like use jquery function that validate a input field. This input field must be used for entering 11 digit numbers that start with 0.
I tried some function but doesn’t work!
function check(mob) {
var firstnum = mob.substring(1);
alert(firstnum);
if (firstnum != "0" || mob.lenght != 11)
return false;
else
return true;
}
function check(mob) {
return mob.substring(0, 1) == '0' && mob.length == 11;
}
String Method Reference
If you want to check is it 11 digit, you should use RegExp
function check(mob) {
return mob.match(/^0\d{10}$/) != null;
}
You need to use .charAt(0) to get the first character of a string. .substring(1) will return the rest of the string minus the first character.
"01234567890".substring(1) = "1234567890"
"01234567890".charAt(0) = "0"
"01234567890".length = 11 (assuming that you have spelled "length" correctly in your code)
Edit: Since you also need to check for digits, you could use a regular expression to verify this (although the whole check could also be done with a regex)
The completed function could therefore be simplified to just:
function isValidMobile(mobileNumber) {
return mobileNumber.charAt(0) == 0 && mobileNumber.length === 11 && /^\d+$/.test(mobileNumber);
}
Or without the regex
function isValidMobile(mobileNumber) {
return mobileNumber.charAt(0) == 0 && mobileNumber.length === 11 && !isNaN(mobileNumber);
}
if (firstnum >= 1 || mob.lenght <= 11) //lenght spell wrong
change to
if (firstnum >= 1 || mob.length<= 11)
you can give it a try
function check(mob) {
var num = parseInt(mob);
if (mob+'' == '0'+num && mob.length == 11)
return true;
else
return false;
}
here what I am doing is that parseInt will give you exact same number without 0 if all characters are numbers, so in the condition I am just adding 0 in starting and checking with mobile number , it will do 2 validation in once , all are number starts with 0 and next validation is for length
Try using a simple regex as below
function check(mob) {
return /^0\d{10}$/.test(mob)
}
function check(mob) {
if(!isNaN(mob)){ // or use parseInt
var firstnum = mob.charAt(0);
alert(firstnum);
if (firstnum != "0" || mob.length != 11) {
return false;
} else {
return true;
}
}
}

regex for javascript pattern match

i'm looking for a regex expression or javascript which alerts me when a number is NOT between 48-47 or NOT between 96-105 or IS NOT 110 OR 190 OR 8 OR 13.
thanks for all the help friends !!
Regex is not appropriate for such specific numeric checks. Just do a few if statements to compare the value you're working with to the specific values and ranges you want to exclude.
var number = 19;
alert('Number is'+(numberIsValid(number) ? 'valid' : 'not valid'));
function numberIsValid(number) {
// test for numeric argument
if ((number - 0) != number)
return false;
// test for specific exclusions
if (number == 110 || number == 190 || number == 8 || number == 13 || number == 48 || number == 47)
return false;
// test for excluded range
if (number >= 96 && number <= 105)
return false;
return true;
}
I agree with Chris's response above, if you want to see what it would look like, it is kind of a mess. I wouldn't really recommend you use this.
Just to rephrase: Number may not be 8,13,47,48,96-105,110
var num = 10;
if (! /^(8|13|47|48|9[6-9]|10[0-5]|110)$/.test(num)) {
alert(num);
}
function allowedIntegers(n){
return !/^([^\d]|8|13|47|48|110|190|96|97|98|99|100|101|102|103|104)$/.test(String(n));
}

Multiple Logical Operators in javascript

I want to check the following
1: Is x a number
2. If x is less that 5 or greater than 15, sound alert
3. If all is ok, callMe()
var x = 10;
if (isNaN(x) && ((x < 5) || (x > 15))) {
alert('not allowed')
}
else
{
callMe();
}
What am I doing wrong?
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
alert('not allowed')
}
else
{
callMe();
}
This way, if x is not a number you go directly to the alert. If it is a number, you go to the next check (is x < 5), and so on.
All the other answers about the && vs || are correct, I just wanted to add another thing:
The isNaN() function only checks whether the parameter is the constant NaN or not. It doesn't check whether the parameter is actually number or not. So:
isNaN(10) == false
isNaN('stackoverflow') == false
isNaN([1,2,3]) == false
isNaN({ 'prop' : 'value'}) == false
isNaN(NaN) == true
In other words, you cannot use it to check whether a given variable contains a number or not. To do that I'd suggest first running the variable through parseInt() or parseFloat() depending on what values you expect there. After that check for isNaN(), because these functions return only numbers or NaN. Also this will make sure that if you have a numeric string then it is also treated like a number.
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
alert('not allowed')
}
else
{
callMe();
}

Categories

Resources