Grouping JavaScript if statements of the same 'smaller than' - javascript

So I have this long if statement.
if(dupeCheck[0].length > 1 || dupeCheck[1].length > 3 || dupeCheck[2].length > 1 || dupeCheck[3].length > 1){
alert('Copy!');
}
It is possible to group together the dupeCheck[0].length > 1 parts? Like:
if((dupeCheck[0].length||dupeCheck[2].length||dupeCheck[3].length) > 1 || dupeCheck[1].length > 3){
alert('Copy!');
}
Or:
if(dupeCheck[0].length||dupeCheck[2].length||dupeCheck[3].length > 1 || dupeCheck[1].length > 3){
alert('Copy!');
}
I tried both, neither of them worked.

Depending on how many tests you need to run you could also try something like this.
function isGreater(minimum){
for(var i=1;i<arguments.length;i++){
if(arguments[i] > minimum){
return true;
}
}
return false;
}
if(isGreater(1, dupeCheck[0].length, dupeCheck[2].length, dupeCheck[3].length) || isGreater(3, dupeCheck[1].length)){
alert('Copy!');
}
This will let you test any number of values against a number e.g.
if(isGreater(5, 0,0,0,0,2,1,2,3,4) || isGreater(7, 1,3,1,2,1,9,2,1)){
alert('Copy!');
}
Since JavaScript will let you pass as many parameters as you want to a function the 2nd to Nth parameters are tested against the 1st parameter "minimum" and as soon as one passes the test the function returns true. You could adjust the logic to test for other conditions or even ensure that all parameters pass the condition not just one.

There is no built-in language construct to do that.
But what you could do is something like this:
if(Math.min(dupeCheck[0].length, dupeCheck[2].length, dupeCheck[3].length) > 1 || dupeCheck[1].length > 3) {
alert('Copy!');
}

Related

Checking whether ANY url is true

I am new to Javascript as well as Jquery , but can not figure out what I am doing wrong. I just want to check if the user is on any of 3 URLs. I just want to check if the user is on either the ABOUT US, MEMSTAFF TEAM or CAREERS sections. That is it. I thought that if I just used the OR (||) operator, this should work. What am I doing wrong?
<script type="text/javascript">
$(document).ready(function() {
// Check if any of these relative URLS are true
if(window.location.href.indexOf("/about-us" || "/memstaff-team" || "/careers") > -1) {
// Alert me if I am in one of the MAIN sections
alert("Your are in one of the MAIN sections");
}
});
</script>
The test
if (window.location.href.indexOf("/about-us" || "/memstaff-team" || "/careers") > -1)
is equivalent to doing
temp = "/about-us" || "/memstaff-team" || "/careers";
if (window.location.href.indexOf(temp) > -1)
Since the || operator just returns the first truthy value, it's effectively doing temp = "/about-us" and just testing for that. "OR" expressions aren't automatically distributed, you need to do it explicitly.
if (window.location.href.indexOf("/about-us") > -1 ||
window.location.href.indexOf("/memstaff-team") > -1 ||
window.location.href.indexOf("/careers") > -1)
But a simpler way is to use a regular expression:
if (window.location.href.match(/\/(about-us|memstaff-team|careers)/))
Here is another way of doing it:
const urls = ["/about-us", "/memstaff-team", "/careers"];
if (urls.some(url => window.location.href.indexOf(url) > -1)) {
alert("...");
}

Using conditional operator to run more than one statement will not work

function isPrime(num) {
//TODO
let primeNum = false;
let prime = (num == 0 || num == 1) ? primeNum = false : (num == 2) ? console.log("2 is prime") :
(num % 2 == 0) ? console.log("num is divisable by 2 therefore is not prime") : {
console.log("number may be prime");
primeNum = true;
}
return primeNum;
}
Im attempting a challenge off of codewars to test if a num is prime. On my final conditional I want to print to console and set a value to primeNum. It seems to work fine if i do one or the other but not both.
I know its possible to do by writing a separate function containing both statements and having it be called instead or that I could use if and else statements but I'm trying to follow best practices here.
If you have to execute multiple things inside a single expression (such as inside one of the parts of the conditional operator), you may use the comma operator inside of parentheses. For example:
const condition = false;
const result = condition ? 'foo' : (
console.log('falsey!'),
'bar'
);
console.log(result);
Or, for your code:
function isPrime(num) {
const primeNum = (num == 0 || num == 1)
? false
: (
num == 2
? ( console.log("2 is prime"), true)
: (
num % 2 == 0
? (console.log("num is divisable by 2 therefore is not prime"), false)
: (console.log("number may be prime"), null)
)
);
return primeNum;
}
const result = isPrime(4);
console.log('4:', result)
But this is not a good idea - it's hard to read, and is not best practice. Better to use standard if/else statements instead.
Adding some brackets should to the trick, or your interpreter doesn't know what belongs to which expression.
Nested ternaries is not exactly best practices. Consider multiple if() return x;

Javascript (-1 <= 5 <= 1) === true?

I want to validate that a given number is within a given range:
function validate(min, max, amount) {
return (min <= amount <= max);
}
But this does not seem to work properly. I know I can do it with two comparison and a logical AND, but I would like to it in one comparison. Is there any NATIVE javascript way to realize this?
Use this instead :
return (min <= amount && amount <= max);
There is no shortcut. And there is a good reason the JavaScript engine can't guess your intent : what you typed was valid, it just isn't interpreted as you'd like. You were testing, in fact
((min <= amount) <= max)
and the result of the first comparison, which is a boolean, is converted to 0 or 1 for the second one (more details here about operators precedence, those comparison operators are left-to-right).
If you really want a shortcut, you could do this :
Number.prototype.isin = function(m,M) {
return m<=this && this<=M;
};
console.log(0.5.isin(1,2)); // logs false
console.log(3..isin(2,5)); // logs true
but I personally would use the standard solution with && that everybody can read and which doesn't involve an additional function call.
Aside : I could have called my function in instead of isin but it might break ES3 browsers.
Operators ( == , <= , < , >= , == ) take only 2 arguments.
When there are more arguments it uses mathematical order of computing. So in fact your code behave like:
min <= amount // true
true <= max // this is illogical
It's also optimal, because when executing logical statements and finding something like:
if(false && (some computing))
It will ignore (some computing) because result will be always false
This is very common practive in every language. Test like this will not have NullPointerException error, because first argument is already false.
if(obj != null && obj.getValue() > 10) //C++,Java, etc.
if(obj !== undefined && obj.val() > 10) // javascript
if(obj.length != 0 && obj.val() > 10) //jQuery

HTML textfield whose values cannot be 0 using Javascript

I was trying to make a javascript function which will check if the user entered value inside a text field cannot be less than 9 digits & it cannot be all 0s.
This is what I made
function CheckField(field)
{
if (field.value.length <9 || field.value=="000000000")
{
alert("fail");
field.focus();
return false;
}
else
{
return true;
}
}
<input type ="text" id="number1" onBlur='return CheckField(this)'>
But this doesnt check the condition where user enters more than 9 values and all 0's. It checks only for 1 condition that is with exact 9 zeros 000000000
So, if I understand that right you want the user to be able to enter a number with more than 9 digits, but they cannot be all zeros, right?
This can be done with a regexp:
var value; // Obtain it somehow
if (/^\d{9,}$/.test(value) && !/^0+$/.test(value)) {
// ok
}
What this checks is whether the value is at lest 9 digits (it does not allow anything but digits) and that they are not all 0s.
This should check for both conditions:
function CheckField(field){
return !/0{9}/.test(field.value) && /\d{9}/.test(field.value);
}
Try something like this:
var valueEntered = field.value;
if (parseInt(valueEntered) == 0) ...
or if you wanted to check if it was a number as well:
if (!(parseInt(valueEntered) > 0))
Two options spring to mind. You can try parsing the value as a number and test for isNaN or != 0
var parsed = parseInt(field.value, 10);
if(field.value.length < 9 || !(isNaN(parsed) || parsed != 0)){
alert("fail");
... rest of code
}
Or you could use a regex
if(field.value.length < 9 || !/[^0]/.test(field.value){
alert("fail");
... rest of code
}
The first option is probably quicker.
try this:
if (field.value.length <9 || field.value.replace("0","") == "")

I need a JQuery IP Mask plugin

Is there a good IP Mask plugin for JQuery? I've tried Masked Input Plugin but it doesn't IP Addresses with less than 12 digits. Then I've tried meioMask and this doesn't work with less than 12 digits either. Any suggestions?
You can find your answer in this post :
http://mlntn.com/2009/12/30/jquery-ip-address-plugin/
and a demo for you to try
http://mlntn.com/demos/jquery-ipaddress/
This is an older post however for someone who wants an easy way to manipulate multiple inputs, without using a bulking plugin, or having to worry about documentation or methods, here's a simple class selector method that does it all for you. Its IPv4 only but it sounds like your needs are pretty simple.
//jQuery 1.9+ selector pattern,
//To get working with an older version
//Swap first line to $(".ip").bind('keydown',function(e){
//To get working with jQuery versions support .live
//$(".ip").live('keydown',function(e){
$(document).on('keydown',".ip",function(e){
var code = e.keyCode || e.which;
var sections = $(this).val().split('.');
//Only check last section!
var isInt = ((code >= 48 && code <= 57) || (code >= 96 && code <= 105));
var hasSlash = $(this).val().indexOf("/") == -1;
if(isInt){
if(hasSlash){
if(sections.length < 4){
//We can add another octet
var val = parseInt(sections[sections.length-1]+String.fromCharCode(code));
if(val > 255 || parseInt(sections[sections.length-1]) == 0){
$(this).val($(this).val()+"."+String.fromCharCode(code));
return false;
}
return true;
} else {
//Lets prevent string manipulations, our string is long enough
var val = parseInt(sections[sections.length-1]+String.fromCharCode(code));
if(val > 255 || parseInt(sections[sections.length-1]) == 0){
return false;
}
return true;
}
} else {
var cidr_split = $(this).val().split('/');
var target_val = parseInt(cidr_split[1]+String.fromCharCode(code));
return (target_val < 33 && target_val.toString().length < 3 && parseInt(cidr_split[1]) != 0);
}
} else if(code == 191){
//CIDR Slash
return ($(this).val().indexOf("/") == -1);
} else if(code == 8 || code == 46 || code == 9 || code == 13){
return true;
}
return false
});
To break this down for understanding, you bind the class "ip" in your input, it will handle the rest automatically :D This version supports CIDR notation (eg: 192.168.1.1/16) it only allows valid addresses to be input, to remove CIDR function you can use use the following snippet (not tested)
//jQuery 1.9+ selector pattern,
//To get working with an older version
//Swap first line to $(".ip").bind('keydown',function(e){
//To get working with jQuery versions support .live
//$(".ip").live('keydown',function(e){
$(document).on('keydown',".ip",function(e){
var code = e.keyCode || e.which;
var sections = $(this).val().split('.');
//Only check last section!
var isInt = ((code >= 48 && code <= 57) || (code >= 96 && code <= 105));
if(isInt){
if(sections.length < 4){
//We can add another octet
var val = parseInt(sections[sections.length-1]+String.fromCharCode(code));
if(val > 255 || parseInt(sections[sections.length-1]) == 0){
$(this).val($(this).val()+"."+String.fromCharCode(code));
return false;
}
return true;
} else {
//Lets prevent string manipulations, our string is long enough
var val = parseInt(sections[sections.length-1]+String.fromCharCode(code));
if(val > 255 || parseInt(sections[sections.length-1]) == 0){
return false;
}
return true;
}
} else if(code == 8 || code == 46 || code == 9 || code == 13){
return true;
}
return false
});
I am providing the code here for two purposes 1) This is something i believe needs to be addressed, 2) i hope to contribute to the world
The snippet is not designed to be pulled apart, nor support IPv6, if you need IPv6 Support please see https://code.google.com/p/jquery-input-ip-address-control/ that anyulled suggested.
But aside from the complex syntax, it breaks the octets apart, and only checks the "active" octet, it supports any VALID address (0.0.0.0, 0.0.0.0/0, ect) so use wisely it does not do any fancy checking other than preventing invalid input. If you're looking for a checker, please see Santiago Elvira Ramirez's post about the IP Address validator.
You could try using this plugin https://code.google.com/p/jquery-input-ip-address-control/
The working examples from the Masked Input Plugin -
http://digitalbush.com/projects/masked-input-plugin/
Are less than 12 characters:
jQuery(function($){
$("#date").mask("99/99/9999");
$("#phone").mask("(999) 999-9999");
$("#tin").mask("99-9999999");
$("#ssn").mask("999-99-9999");
});
They have working examples which are running perfectly?
What is exatly is your issue and can you post anymore in depth information?
jQuery(function($){
$("#MyElementID").mask("10.0.0.0"); //Does this not work?
});
Are you trying to counter for 1-3 digits in each field?
eg to be able to.
$("#MyElementID").mask("1.0.0.0"); //this
$("#MyElementID").mask("10.10.10.10"); //or this
$("#MyElementID").mask("100.100.100.100"); //or this
If you be more descriptive you can get help..
If you are after that you can try something simpler by watermarking the input box rather than enforcing a mask, so you can vary the numbers that can be entered.
See Jquery-Watermark - http://code.google.com/p/jquery-watermark/
i found this and you donĀ“t need to install plugins
function fnValidateIPAddress(ipaddr) {
//Remember, this function will validate only Class C IP.
//change to other IP Classes as you need
ipaddr = ipaddr.replace( /\s/g, "") //remove spaces for checking
var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; //regex. check for digits and in
//all 4 quadrants of the IP
if (re.test(ipaddr)) {
//split into units with dots "."
var parts = ipaddr.split(".");
//if the first unit/quadrant of the IP is zero
if (parseInt(parseFloat(parts[0])) == 0) {
return false;
}
//if the fourth unit/quadrant of the IP is zero
if (parseInt(parseFloat(parts[3])) == 0) {
return false;
}
//if any part is greater than 255
for (var i=0; i<parts.length; i++) {
if (parseInt(parseFloat(parts[i])) > 255){
return false;
}
}
return true;
} else {
return false;
}
}

Categories