I have been trying to write a function that finds the difference in two dates, and if the two dates are not 20 days or more apart an error message appears after the user clicks out of the form field. The code below is supposed to do this. However, seeing as I am really new to JavaScript I would greatly appreciate some help and/or advice as how to fix my problem.
`
<html>
<head><title>Form test page</title></head>
<body>
<link rel="stylesheet" type="text/css" href="OnbordingInStyle.css">
<script>
function dateerror() {
var c = 21;
var x = date ();
var y = document.getElementById('expected_start_date').value == "";
if ( x + c - y <= 0) {
datecrossover += "Attention this date is less than three weeks away, please be ready to expect delays with equipment for new employees \n";
}
if (datecrossover !="") {
alert(datecrossover);
return false;
}
}
</script>
<form method="post" action="Test.php" onsubmit="return dateerror()">
<table>
<tr>
<td>
<label for="expectedstartdate">Expected Start Date</label>
</td>
<td><div class="required">
<input type="date" name="expected_start_date" id="expected_start_date" size="15" maxlength="10" />*</div>
</td>
</tr>
<tr>
<td>
<input type="hidden" name="date_completed" id="date_completed" />
<script>
document.getElementById('date_completed').value = Date();
</script>
</td>
</tr>
<tr>
<td>
<input type="submit" name="Submit" value="submit" />
<input type="reset" name="reset" />
</td>
</tr>
</table>
</form>
</body>
</html>
`
If you paste this into a new .html file - it should work :)
<link href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.min.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
$( "#datepicker2" ).datepicker();
});
</script>
<br><br><center>
<form action="" method="POST">
<input type="text" name="nowdate" id="datepicker" value="07/01/2014">
<input type="text" name="wantdate" id="datepicker2" value="07/31/2014">
<input type="submit" name="submitJS" id="submitJS" value="Submit" onclick="return ajaxSubmit();">
</form>
<script>
function parseDate(str) {
var mdy = str.split('/')
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function daydiff(first, second) {
return (second-first)/(1000*60*60*24);
}
function ajaxSubmit() {
var date1 = $('#datepicker').val();
var date2 = $('#datepicker2').val();
//alert(date1 + " " + date2);
datediff = daydiff(parseDate($('#datepicker').val()), parseDate($('#datepicker2').val()));
if(datediff != 21) { alert("These dates are not 21 days apart"); }
return false;
}
</script>
This line
var y = document.getElementById('expected_start_date').value == "";
looks suspicious to me. It is setting y to 1 or 0 depending on whether the expected start date is set, but it seems from your question that what you really wanted was
var y = document.getElementById('expected_start_date').value;
You need to instantiate the date as a Date object. For example,
var x = new Date(Date.now());
That would set up a date with the current date and time. I'd recommend looking up the JavaScript reference at developer.Mozilla.com to learn more.
Related
I have wrote a code to split the input into two variables i.e. year and month. But, I am unable to make it work. It does not return the total number of months into the respective text field. Please help me debug my code.
$(function() {
$("#duration").keyup(function() {
var input = document.getElementById('duration').value;
var fields = input.split('.');
var years = fields[0];
var months = fields[1];
var result = years.val() * 12 + months.val();
document.getElementById("totalNumMonths").innerHTML = result;
});
});
<html>
<body>
<table>
<tr>
<td>Calculate Months</td>
<td>
<label>Input Years in the format (year.month e.g. 11.6)</label>
<input class="form-control" name="duration" id="duration" value="" type="number" />
<br/>
<label>Total Months</label>
<input class="form-control" name="totalNumMonths" id="totalNumMonths" value="" type="number" />
</td>
</tr>
</table>
</body>
</html>
Issues with code that I identified and fixed.
You dont need to access years.val() and months.val() because years and months holds string value.
If your input doesnot have a dot, the value for months will be undefined, so you can define years and months as fields[0] || "0" and fields[1] || "0" respectiveley.
Since element with id totalNumMonths is an input. You should set the value and not innerHTML
Since the years and months value produces a string, I have added a + symbol infront of them while setting the value for #totalNumMonths to convert them to number, since we are performing numiric action. Else + symbol on string will perform string concatenation.
Working Fiddle
$(function () {
$("#duration").keyup(function () {
var input = document.getElementById('duration').value;
var fields = input.split('.');
var years = fields[0] || "0";
var months = fields[1] || "0";
var result = +years * 12 + +months;
document.getElementById("totalNumMonths").value = result;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<table>
<tr>
<td>Calculate Months</td>
<td>
<label>Input Years in the format (year.month e.g. 11.6)</label>
<input class="form-control" name="duration" id="duration" value="" type="number" />
<br />
<label>Total Months</label>
<input class="form-control" name="totalNumMonths" id="totalNumMonths" value="" type="number" />
</td>
</tr>
</table>
You were calling val on string elements, which caused errors. And the result was adding months as a string value.
$(function () {
$("#duration").keyup(function () {
var input = document.getElementById('duration').value;
var fields = input.split('.');
var years = parseInt(fields[0]);
var months = parseInt(fields[1]);
var result = (years * 12) + months;
document.getElementById("totalNumMonths").value = result;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<table>
<tr>
<td>Calculate Months</td>
<td>
<label>Input Years in the format (year.month e.g. 11.6)</label>
<input class="form-control" name="duration" id="duration" value="" type="number"/>
<br/>
<label>Total Months</label>
<input class="form-control" name="totalNumMonths" id="totalNumMonths" value="" type="number"/>
</td>
</tr>
</table>
</body>
</html>
In the code snippet, you are having the value of years & months in the respective variables, so you don't need to use years.val() to get that value.
Check this out!!
$(function() {
$("#duration").keyup(function() {
var input = document.getElementById('duration').value;
var fields = input.split('.');
var years = fields[0];
var months = fields[1] || 0;
var result = years * 12 + months;
document.getElementById("totalNumMonths").innerHTML = result;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>Calculate Months</td>
<td>
<label>Input Years in the format (year.month e.g. 11.6)</label>
<input class="form-control" name="duration" id="duration" value="" type="number" />
<br/>
<label>Total Months :</label>
<!-- <input class="form-control" name="totalNumMonths" id="totalNumMonths" value="" type="number" /> -->
<span id="totalNumMonths">0</span>
</td>
</tr>
</table>
Hi I am new to software development and working on code. I am trying to get cookies to populate a field in my form when a user has input into it previously. However not able to work it out.
I have tried to setcookies and getcookies to work , however just cannot populate the form value for some reason. I am getting undefined in the field.
<script>
var today = new Date();
var expiry = new Date(today.getTime() + 30 * 24 * 3600 * 1000); // plus 30 days
function setCookie(name, value) {
document.cookie = name + "=" + escape(value) + "; path=/; expires=" +
expiry.toGMTString();
}
</script>
<script>
function storeValues(form) {
setCookie("phoneNumber", form.phoneNumber.value);
return true;
}
</script>
<script type="text/javascript">
function getCookie(name) {
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
</script>
<body>
<form name="contactInfo" id="contactInfo" autocomplete="on" action="/javascript/getcookie/" onsubmit="storeValues(this)">
<fieldset>
<legend>How can we reach you ?</legend>
<div>
<label style="width: 40%;" for="phoneNumber">What number can we call
you on ? <font color="red">*</font> </label>
<input name="phoneNumber" type="tel" id="phoneNumber" placeholder="e.g. 0412345678" onfocus="this.placeholder=''" onblur="this.placeholder='e.g. 0412345678' ; validatePhoneNumber(this)" required>
<input type="submit" class="submit" id="post-btn" value="Call Me" />
</form>
<script>
document.getElementById("phoneNumber").value = document.write(getCookie("phoneNumber"));
</script>
</body>
I am expecting to get the number that i previously entered into the form to populate the next time I load the page.
Try to use the sessionStorage instead of cookiee .
It saves a lot of coding hack.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<body onLoad="getSession()">
<form >
<fieldset>
<legend>How can we reach you ?</legend>
<div>
<label style="width: 40%;" for="phoneNumber">What number can we call
you on ? <font color="red">*</font> </label>
<input name="phoneNumber" type="tel" id="phoneNumber" placeholder="e.g. 0412345678" required>
<!-- <button onClick="validatePhoneNumber(this)">Submit</button> -->
<input type="submit" class="submit" id="post-btn" value="Call Me" onClick="validatePhoneNumber(this)"/>
</form>
</body>
</html>
<script>
function validatePhoneNumber(){
var value = document.getElementById("phoneNumber").value;
console.log(value)
sessionStorage.setItem("phoneNumber", value);
}
function getSession(){
console.log("hey");
var session = sessionStorage.getItem("phoneNumber");
document.getElementById("phoneNumber").setAttribute("value" , session);
}
</script>
Notice :- Removed some attribute and field because i am not having that data , you can add according to your necessity .
For more detail about sessionStorage , visit LINK
Hi guys im a grade 10 student and was asked to create a basic like calculator to solve for the area of the triangle, but i really dont know how.I can do it with the use of a radio button but my teacher said to do it without the radio input. My codes works fine but if i press clear and input a value to the base and height, it will say syntax error...please can you help me? also whenever i dont put a value on base and height,it says 0 instead of syntax error,so please help me....(also sorry about earlier, im just new to this site)
this is my code:
<html>
<head>
<title>hfsabfhsabfihs</title>
</head>
<body>
<script type="text/javascript">
<!--
function checkbutton() {
var num1 = document.getElementById("input1").value;
var num2 = document.getElementById("input2").value;
if (document.form1.checked == false) {
alert("Syntax Error")
} else {
alert(num1 * num2 / 2);
}
}
function clearbutton() {
document.form1.checked = false;
var num1 = document.getElementById("input1").value = "";
var num2 = document.getElementById("input2").value = "";
}
//-->
</script>
<form name="form1">
<table>
<tr>
<td>Base</td>
<td><input type="text" id="input1" /></td>
</tr>
<tr>
<td>Height</td>
<td><input type="text" id="input2" /></td>
</tr>
</table>
<input type="button" value="Compute" onclick="checkbutton()">
<input type="button" value="Clear" onclick="clearbutton()">
</body>
</html>
problem is on clear function function
function clearbutton()
{
// document.form1.checked= false;
var num1 = document.getElementById("input1").value="";
var num2 = document.getElementById("input2").value="";
}
you are getting this error because you have set a variable here i.e form1.checked. either remove this variable or change its value on calculation function
Hope the below code helps:
// vairbale
const baseInput = document.querySelector("#input1")
const heightInput = document.querySelector("#input2")
const coputeBTn = document.querySelector("#Compute")
const areaTriangle = (base, height) =>{
let total =""
let error = false
let errorMessage = ""
if(base != "" && height != ""){
error = false
total = base * height / 2
}else{
error = true
errorMessage = "Please fill all inputs."
return errorMessage
}
return total
}
// Calling Function
coputeBTn.addEventListener("click", ()=>{
console.log(areaTriangle(Number(baseInput.value), Number(heightInput.value)))
})
<!doctype HTML>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form name="form1">
<table>
<tr>
<td>Base</td>
<td><input type="text" id="input1" /></td>
</tr>
<tr>
<td>Height</td>
<td><input type="text" id="input2" /></td>
</tr>
</table>
<input type="button" id="Compute" value="Compute">
<input type="button" value="Clear" onclick="clearbutton()">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Smart Hotel - Check In Report</title>
<link rel="stylesheet" type="text/css" href="xxxxindex.css"/>
<link rel="stylesheet" type="text/css" href="xxxxform.css"/>
<script>
window.onload = function()
{
defaultDate();
}
function defaultDate()
{
var today = new Date();
document.getElementById("displayDate").value = [today.getDate(), today.getMonth()+1, .getFullYear()].join('/');}
</script>
</head>
<body>
<div id="screen">
<div id="wrapper">
<div class="roundContainer" id="menuBar">
<?php include("./menu.php")?>
</div> <!-- topContainer -->
<div class="roundContainer" id="main">
<form action="" method="Post" onsubmit="return confirm('Are you sure you want to display Check Ins?')">
<div id="formWrapper">
<h3>Check In Report</h3>
<div class="textInput">
<fieldset>
<label for="date">Display Report Since: </label>
<input type="date" id = "displayDate" style="cursor:pointer;" /><br>
</fieldset>
</div>
<div class="subInput">
<fieldset>
<input type="reset" value="Clear" name="clearB" style="width: 90px;cursor:pointer;">
<input type="submit" value="Display" name="submitB" style="width: 90px;cursor:pointer;">
</fieldset>
</div></div></form></div> <!-- formWrapper --></div> <!-- mainContainer -->
</div> <!-- Wrapper -->
<div id="userMenu">
<?php include("./userMenu.php")?>
</div> <!-- userMenu -->
</div> <!-- Screen -->
</body>
</html>
I have tried so many combinations, tried PhP functions and echo in the value tag inside the input, tried the
onload ="defaultDate()"
inside the tag, but no matter what I do, I keep getting nothing, just the normal dd/mm/yyyy in the date box.
I would appreciate any help, I have looked into all the answers given before to similar problems and none of them actually works.
Thank you.
If you havn't particular needs, you should launch the function when the page loads (with window.onload).
I've also edited a bit your function to show the date in the dd/mm/yyyy format. Here's the code:
window.onload = function(){
defaultDate()
};
function defaultDate()
{
var today = new Date();
document.getElementById("displayDate").value = [today.getDate(), today.getMonth()+1, .getFullYear()].join('/');
}
The scripts in the head are executed before the DOM is ready therefore your displayDate doesn't exist.
You have two choices:
- Make your code wait for the DOM to be ready
- Put your script at the bottom of the page (Simpler but uglier)
var d= new Date();
var year= d.getFullYear();
var month= d.getMonth();
var date=d.getDate();
var day= d.getDay();
var h= leftPad(d.getHours(), 2);
var m= leftPad(d.getMinutes(), 2);
var s= leftPad(d.getSeconds(), 2);
var time= (h%12==0?"12":h%12) + ":" + m + ":" + s + (h>11?" PM":" AM");
$("#date-time").html("Today is "+ mos[month] + " " + date + ", " + year + " (" + days[day] +") + time);
Currently working on an "retirement calculator" where I have to generate a table for money-saved each year based on data entered into the first two forms. Unfortunately I can't figure out why it's not appending the table to the site. I don't receive any errors on the console.
I'm also a complete novice at JS/JQ. The code for calculate is near the bottom. I realize it may look at little all over the place, I'm trying to get it to work first before I got back and clean it up some.
EDIT: I took out some methods so there isn't so much to traverse. Assume that the variables involved in calculate are set to real values (aka they're not null/NaN).For example there's an add JQuery method that'll add more scenarios. But since it distracts from the problem I took it out. But the for loop runs in relation to the array
var scenarioCount=0;
var hasError=false
var error=false;
var YOB;
var CurrSav;
var RetAge;
var LifeExp;
var Year;
var scenarios = new Array();
$(document).ready(function ()
{
$('#calculate').on('click', function(e)
{
if(!isBasicInfoValid()) //check to see if basic info is correct
{
if(!error) //if there isn't already an error put one
{
$('#basic').append($("<div class='basicError'>Input is not valid! </div>"));
}
resetVars(); //reset the variables
error=true; //say there is an error on screen
}
else
{
$("#basic .basicError").remove();
error=false;
calculate();
}
e.preventDefault();
});
});
function calculate()
{
var body = document.getElementById('body');
//body is null right here for some reason
$(body).append("<div id='results' class='form'>");
for(var i=0;i<scenarios.length;i++)
{
var element = scenarios[i];
var n = parseInt(YOB)+parseInt(RetAge)-Year;
var m = LifeExp-RetAge;
var r = 1+element.workRate;
var g = 1 + element.retiredRate;
var I = CurrSav;
var T = element.retIncome;
var part1 = (T/Math.pow(g,m-1))*((1-Math.pow(g,m))/(1-g))-(I*Math.pow(r,n));
var S = part1*(1-r)/(1-Math.pow(r,n));
var savings=I;
$('#results').append("<div><h4>You need to save "+S+" dollars</h4></div>")
$('#results').append("<table id=t><tr><th>Year</th><th>Money Saved</th></tr>");
for(var j=n;j>0;j--)
{
savings=S+savings*r;
$('#t').append("<tr><td>"+j+"</td><td>"+savings+"</td></tr>")
}
for(var j=m;j>0;j--)
{
savings=(savings-T)*g;
$('#t').append("<tr><td>"+j+"</td><td>"+savings+"</td></tr>")
}
$('#results').append("</table></div>");
}
};
function resetVars()
{
YOB=null;
CurrSav=null;
RetAge=null;
LifeExp=null;
Year=null;
}
function scenarioObject()
{
var obj={
nameScen : document.forms["scenario"]["ScenarioName"].value,
workRate : document.forms["scenario"]["Working"].value,
retiredRate : document.forms["scenario"]["Retired"].value,
retIncome : document.forms["scenario"]["desiredInc"].value
}
return obj;
}
<!DOCTYPE html>
<html>
<head>
<title>Assignment 3</title>
<link rel='stylesheet' type='text/css' href='/uncSemester7/comp426/a3/assignment3.css'>
<script src='/uncSemester7/comp426/a3/jquery-1.10.2.js'></script>
<script src='/uncSemester7/comp426/a3/assignment3.js'></script>
</head>
<body>
<div class='form'>
<h3> Basic Information </h3>
<form id='basic'>
<div>Year of Birth: <input type='number' name='YOB'> </div>
<div>Current Savings: <input type='number' name='CurrSav'>
</div>
<div>Expected Retirement Age: <input type='number' name='RetAge'></div>
<div>Life expectancy: <input type='number' name='LifeExp'>
</div>
</form>
</div>
<div id='scenDiv' class='form'>
<div id='buttons'>
<div><button id='add' type='submit'>Add Scenario </button></div>
<div><button id='calculate' type='submit'> Calculate </button></div>
</div>
<h3> Scenario </h3>
<form id='scenario'>
<div>Name: <input type='text' name='ScenarioName'> </div>
<div>Rate of Investment Return (While Working): <input type='number' name='Working'></div>
<div>Rate of Investment Return (Retired): <input type='number' name='Retired'></div>
<div>Desired Retirement Yearly Income: <input type='number' name='desiredInc'></div>
</form>
</div>
</body>
</html>
You're using getElementById('body'), where you should be using getElementsByTagName('body')[0], as body is not an id, but a tag. Or better yet with jQuery since you're already using it, $('body').