Can't get javascript to popup alert for leap year - javascript

<button onclick="isleap(1992)">Try it</button>​
function isleap(year);
{
var yr=document.getElementById("year").value;
if ((parseInt(yr)%4) == 0)
{
if (parseInt(yr)%100 == 0)
{
if (parseInt(yr)%400 != 0)
{
alert("Not Leap");
return "false";
}
if (parseInt(yr)%400 == 0)
{
alert("Leap");
return "true";
}
}
if (parseInt(yr)%100 != 0)
{
alert("Leap");
return "true";
}
}
if ((parseInt(yr)%4) != 0)
{
alert("Not Leap");
return "false";
}
}
​
http://jsfiddle.net/kcyCd/
Having problems figuring out how to get the code to popup the alert box with the answer to the leap year.

A simple isLeapYear function is:
function isLeapYear(year) {
var d = new Date(year, 1, 29);
return d.getMonth() == 1;
}
It just sees if 29 February occurs in the given year. You should be able to do:
function isLeapYear2(year) {
return !!Date.parse(year + '-02-29');
}
on the basis that parsing an invalid date should return NaN, which type-converts to false, but not all browsers correctly implement Date.parse. e.g.
isLeapYear2('2001'); // false in Firefox, true in IE

<button onclick="alert(isleap(1992));">Try it</button>
If you alert the value returned from the isleap function it should work. I'm not guaranteeing the answer that pops up will be correct though.

Your fiddle doesn't work because you've kept the default jsfiddle setting that places your JS in an onload handler, which means your function isn't global and isn't accessible from the inline onclick attribute - this should be changed in the drop-down on the left to one of the "no wrap" settings. Also, the first thing the function would do if called is try to read the value from an element with id "year" and you have no such element. You currently ignore the year parameter.
Having said that, your function is way more complicated than it needs to be. You can greatly simplify your code by doing the parseInt() once at the beginning, then do whatever it is you need to do if the value being tested isn't an integer, and then you can do the leap year test in just one line.
Also, if you're using parseInt() on user input you must specify a radix as the second parameter if you want to avoid obscure bugs due to input starting with a leading zero being treated as octal. So parseInt(year, 10).
Finally, why return strings "true" and "false"? Wouldn't it make more sense to return actual booleans so that you can call your function as:
if (isleap(1992)) {
// do something
}
Anyway, here's a short version:
function isleap(year) {
year = parseInt(year,10);
if (isNaN(year)) {
alert("Not a number");
return false;
}
if (year%4===0 && (year%100!=0 || year%400===0)) {
alert("Leap");
return true;
} else {
alert("Not leap");
return false;
}
}
Demo: http://jsfiddle.net/kcyCd/1/
If you didn't need to display the alert you could make it shorter still:
function isleap(year) {
year = parseInt(year,10);
if (isNaN(year)) {
alert("Not a number");
return false;
}
return (year%4===0 && (year%100!=0 || year%400===0));
}
And obviously it would be a one-liner if you didn't need to test for invalid values.

You're passing a value into the function, and then looking for a different value in the DOM that doesn't exist.
Also, the code is hard to follow since you merged true/false conditionals, and you're using a string instead of a boolean - which is bad, because if(isleap(1992)) will always be true in your code.
Simplified:
function isleap(year)
{
if(year % 4 == 0 || (year % 100 == 0 && year % 400 == 0)){
return true;
}
return false;
}

Related

Find the output using typeof function

I am writing a code. And here I have a problem how can I fix that. I have an input line, it takes a string or a number. So I need to check what is the output and get the answer. I need to give a simple solution. So I can't use functions or something like that.
let input = prompt('Enter your text.');
if (typeof input === "string") {
alert("You have string.");
} else if (typeof input === "number" && input > 30) {
alert("number more than 30");
} else if (typeof input === "number" && input < 30) {
alert("number less then 30");
}
prompt will always return a string.
If you want to check whether the string is composed purely of numerical values, you could use a regular expression:
if (/^[+-]?\d+(?:\.\d+)?$/.test(input)) {
// then it's purely numerical
const num = Number(input.trim());
// perform more operations on the number
} else {
// it's not composed of only numerical characters
}
If you don't want to use a regex, you can use Number alone, but then you'll also include values like Infinity which might not be desirable, and since Number('') gives 0, you'll have to check for that separately:
const num = Number(input);
if (input.trim().length && !Number.isNaN(num)) {
// then it's a number, use num
}
Another approach that I'd recommend is to avoid prompt entirely. Consider using a proper modal instead, such as a form with an input box and a submit button.
In such a case, if you want to require a numeric input, just do:
<input type="number">
I had a similar problem a few weeks ago and this is what I did:
function testNumber(test) {
if (isNaN(test) === false) {
console.log("this is a number");
} else {
console.log("this is not a number");
}
}
testNumber(4); // number
testNumber("4") // number
testNumber("string") // not a number
You can replace "test" for a variable if you don't want to use a function
if (isNaN(myVar) === false) {}
And you may want to add more checks if you want to differentiate between 4 and "4"
You can do
let input = prompt('Enter your text.');
if(isNaN(Number(input))){alert("You have string.")};
if (Number(input) > 30) {
alert("number more than 30");
} else if (Number(input) < 30) {
alert("number less then 30");
}
So it can change all Stringed-numbers to numbers and check if they are number with the isNaN function

Javascript Eval() thinks first value is a function

I am writing a function that will evaluate expressions in an input field and return the sum.
Currently is working but I am running into an error that I just cannot figure out. Here is my code in Plunker.
function linkFunction(scope) {
var PO = 10;
scope.value = PO;
scope.result = '';
scope.Evaluate = function (input) {
if (input.match(/[a-zA-Z]/g) != null) { //to check if user has inputted a letter between a-z, case sensitive.
return alert("You must only use numbers, not letters")
} else if (input.match(/[!"^£$&[{}\]?\\##~<>_'|`¬:;,=]/g) != null) { //to check if user has inputted a special symbol
return alert("You must only use the symbols specified")
} else if (input.match(/\.\d*\.+/g) != null) { //to check if user has inputted a doubled decimal eg 10.2.2
return alert("You can only use 1 decimal point")
} else if (input.match(/\.{2,}/g) != null) {//to check if user has inputted a two decimals eg 10..1
return alert("You cannot put two decimals one after another")
}
// if (input.match(/\d*\(\d\W\d\)/g) != null){
// }
var percentPattern = /[0-9]*\.?[0-9]+%/g;
var expressionResults = input.match(percentPattern);
if (scope.enablePercentage) { //if parameter = 1, then do this code.
if (expressionResults != null) { //if user has entered into the input field
if (expressionResults.length > 1) { //if you user has finished the RegEx (%, is the end of the RegEx, so code will think its the end of the array, therefore you cannot add another %)
return alert("Too many % values");
} else {// user has met all requirements
var percentageValue = parseFloat(expressionResults) * PO / 100;
input = input.replace(expressionResults, percentageValue);
}
}
} else if (expressionResults != null) { //if parameter = 0, then do this code. Parameter is off, but user has entered percentage
return alert("You cannot use %");
}
scope.result = eval(input);
}
}});
If you write 10(5+3) it gives you an error
TypeError: 10 is not a function
Obviously if a user ran this code they would expect to see the value 80.
Eval thinks that 10() is a function.
Does anyone know how to fix this problem. Thanks
eval expects you to pass it JavaScript, not algebra.
If you want to multiply two values together then you must use a Multiplicative Operator.
10 * (5+3)

What is wrong with this number script?

I'm very new to JavaScript and I want to do an input check.
Here is my script:
function checkInp()
{
var x=document.forms["myForm"]["num"].value; // Get the value
if (isNaN(x))
{
alert("Not a number!"); // Check if the input is a number
return false;
}
var valuex=document.forms["myForm"]["num"].value; // Get the value, i don't know if i have to re-write this variable, if no, please comment.
Number(valuex); // Make the input a number
if (valuex.value > 480) {
alert("Too high!"); // See if the number is greater than 480. If yes, say that, if not, return normally.
return false;
}
else {
return;
}
}
I don't know what happens, but the script doesn't work since I added the second part (to check if the number is greater than 480).
Please help me, with full example if possible.
If i'm not wrong, i thnk you need just to do like this:
If(valuex > 480)..
The way I'll doing it:
Document selectorQuery is more understandable
Dont get the value multiple time
Use ParseInt to transform your var on number
Don't forget to return true if success
Code:
function checkInp() {
var x = document.querySelector('input[name="num"]').value;
if (isNaN(x)) {
alert("Must be a number");
return false
} else if (x > 480) {
alert("Must be under 480");
return false
}
return true
}

Validate specific format without using "-" to split the string

Hi i need to validate a string before sending my form, the format must be
LLLL999999XXX
Where L is any letter
9 is any number
X is any letter or number.
I figure out how to do this using - to split, the problem is that my users use to enter this value with out the - , so its going to be strage if i ask for a - in the format. (in this moment i ask , pls enter format LLLL-999999-XXX wich is no good.)
How can i validate this, without using - , any ideas? sorry im newbie at javascript
<script language="JavaScript">
function RFC(cual)
{
mensaje = "pls enter this format LLLL-999999-XXX"
pat = /[a-z]|[A-Z]/
pat2 = /[a-z]|[A-Z]|[0-9]/
val = cual.split("-")
if (val.length == 3){
if(val[0].length == 4){
if(!comp(val[0],pat)){
alert( mensaje)
return false
}
}
if(val[1].length == 6){
if(isNaN(val[1])){
alert('no es un numero')
return false
}
}
if(val[2].length == 3){
if(!comp(val[2],pat2)){
alert(mensaje)
return false
}
}
else{
alert(mensaje)
return false
}
}
else{
alert(mensaje)
return false
}
return true
}
function comp(cual,pa){
for(m=0;m<cual.length;m++){
if(!pa.test(cual.charAt(m))){
return false
break
}
}
return true
}
</script>
You could just use the regex as below:
/^[a-z]{4}[0-9]{6}[a-z0-9]{3}$/i
If you want - as optional:
/^[a-z]{4}-?[0-9]{6}-?[a-z0-9]{3}$/i
UPDATED:
var input = "LLLL999999XXX";
var pattern = /^[a-zA-Z]{4}\d{6}[a-zA-Z0-9]{3}$/;
if( input.match(pattern) ){
alert("true");
}else{
alert("false");
}
See the working code at:
JsFiddle

How to validate time using && in ajax

I'm working with a time validation and I'm confused on how to validate this start_time and end_time using &&. I have this code so far:
var re = /^(\d{1,2}):(\d{2})([ap]m)?$/;
//Start Time
if($('.start_time').val() != '') {
if(regs = $('.start_time').val().match(re)) {
if(regs[3]) {
// 12-hour value between 1 and 12
if(regs[1] < 1 || regs[1] > 12) {
$('.start_time_error').html('<div>Invalid value for hour(s)</div>');
$('.start_time').focus();
return false;
}
} else {
if(regs[1] > 12){
$('.start_time_error').html('<div>Invalid value for hour(s)</div>');
return false;
}
}
// minute value between 0 and 59
if(regs[2] > 59) {
$('.start_time_error').html('<div>Invalid value for minute(s)</div>');
$('.start_time').val().focus();
return false;
}
} else {
$('.start_time_error').html('<div>Invalid time format</div>');
$('.start_time').focus();
return false;
}
$('.start_time_error').html('<div>Checked</div>');
return true;
}else{
$('.start_time_error').html('<div>Please fill up</div>');
return false;
}
//End time----------
if($('.end_time').val() != '') {
if(regs = $('.end_time').val().match(re)) {
if(regs[3]) {
// 12-hour value between 1 and 12
if(regs[1] < 1 || regs[1] > 12) {
$('.end_time_error').html('<div>Invalid value for hour(s)</div>');
$('.end_time').focus();
return false;
}
} else {
if(regs[1] > 12){
$('.end_time_error').html('<div>Invalid value for hour(s)</div>');
return false;
}
}
// minute value between 0 and 59
if(regs[2] > 59) {
$('.end_time_error').html('<div>Invalid value for minute(s)</div>');
$('.end_time').val().focus();
return false;
}
} else {
$('.end_time_error').html('<div>Invalid time format</div>');
$('.end_time').focus();
return false;
}
$('.end_time_error').html('<div>Checked</div>');
return true;
}else{
$('.end_time_error').html('<div>Please fill up</div>');
return false;
}
I tried something like:
if(regs = $('.start_time').val().match(re) && regss == $('.end_time').val().match(re) )
But didn't work for me it sends and error regss is not defined. Any alternatives on how to do it? Thanks!
I think you're complicating things... Think about separation of concerns. In your logic you have 2 main blocks, the validation for the time string, and the DOM manipulation to extract those values and print the error. In your current code you're repeating the same logic twice for two fields, why not abstract that into a function?
Then I think is not worth printing multiple errors, if the time is invalid, then say something like "you entered an invalid time" and let the user know the right format, with a placeholder in the input, or in the generic error message.
If you follow this advice you can probably reduce your code by a lot and make cleaner and easier to understand. Here's an example, I adapted the regex from this question:
function isTime(str) {
return /^([1-9]|1[012]):[0-5][0-9]\s*?(am|pm)$/i.test(str);
}
Now you can validate your inputs like so:
var start = $.trim($('.start_time').val())
, end = $.trim($('.end_time').val());
if (!isTime(start) || !isTime(end)) {
$('.generic_error').html('<div>Please enter a valid time (HH:MM AM/PM)</div>');
}
Not sure about your HMTL but this should give an overall idea on how to abstract your code to make it DRY (Don't Repeat Yourself).
Demo: http://jsbin.com/ayAbUyI/1/edit

Categories

Resources