Add minutes to time object - javascript

I have three input fields and this javascript:
function deductMinutes(time, minsToDeduct) {
function D(J){ return (J<10? '0':'') + J};
var inputTime = document.getElementById("time").value;
var deductMins = ('75');
var piece = time.split(':');
var mins = piece[0]*60 + +piece[1] + -minsToDeduct;
return D(mins%(24*60)/60 | 0) + ':' + D(mins%60);
}
document.getElementById('start_time').value=(deductMinutes('18:30', '75')); // '17:15'
function addMinutes(time, minsToAdd) {
function D(J){ return (J<10? '0':'') + J};
var inputTime = document.getElementById("time").value;
var addMins = ('20');
var piece = time.split(':');
var mins = piece[0]*60 + +piece[1] + +minsToAdd;
return D(mins%(24*60)/60 | 0) + ':' + D(mins%60);
}
document.getElementById('end_time').value=(addMinutes('18:30', '20')); // '18:50'
<html>
<head>
<title>JavaScript setMinutes Method</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.js"></script>
</head>
<body>
<p><label>Select time: </label><input type="text" id="time" name="time" onChange="addMinutes(this.value)" /></p>
<p><label>Start time: <input type="text" id="start_time" name="start_time" readonly="readonly" /> less 75 minutes</label></p>
<p><label>End time: <input type="text" id="end_time" name="end_time" readonly="readonly" /> plus 20 minutes</label></p>
</body>
</html>
I need 75 minutes to be deducted from the time value entered in the first input ("time") from a timepicker, and entered into the second field ("start_time"), then 20 minutes added to the time value and entered into the third field ("end_time"). Currently it works with a predifined time in the calculation being 18:30 in the last line, but I need this to be replaced with whatever the user selects into the 'time' field input.
Aaaaarrrgghh! I have gotten so far with this darn thing, but can't get past this last bit!
Can anyone please help?

Related

Uncaught ReferenceError: $function is not defined

The purpose of this function is to load a timestamp by default into a form element, but it appears this javascript function is never loaded when the HTML renders.
<!DOCTYPE html>
<html>
<script type=”text/javascript”>
function Timestamp() {
const currentTime = new Date();
var year = currentTime.getFullYear();
var month = currentTime.getMonth();
var day = currentTime.getDate();
var dash = "-";
var space = " ";
var colon = ":";
var hour = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var timestamp = year.concat(dash, month, dash, day, space, hour, colon, minutes, colon, seconds);
document.getElementById("curr").innerHTML = timestamp;
console.log(timestamp);
}
</script>
<head>
<title>Create New Reservation</title>
</head>
<body onload="Timestamp()">
<h1>Enter Reservation Details</h1>
<h3>Current Time: <span id="curr"></span></h3>
<form method="post" action="form.php">
<fieldset>
<label>Current Time</label>
<type="text" />
<input type="text" id="occurred" name="occurred">
</form>
</body>
</html>
The console outputs the following error:
"Uncaught ReferenceError: Timestamp is not defined"
”text/javascript” will not work. use "text/javascript"
<!DOCTYPE html>
<html>
<head>
<title>Create New Reservation</title>
</head>
<body onload="Timestamp()">
<h1>Enter Reservation Details</h1>
<h3>Current Time: <span id="curr"></span></h3>
<form method="post" action="form.php">
<label>Current Time</label>
<type="text" />
<input type="text" id="occurred" name="occurred">
</form>
<script>
function Timestamp() {
const currentTime = new Date();
var year = currentTime.getFullYear();
var month = currentTime.getMonth();
var day = currentTime.getDate();
var dash = "-";
var space = " ";
var colon = ":";
var hour = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var timestamp = year + dash + month + dash+ day+ space+ hour+ colon+ minutes+ colon+ seconds;
document.getElementById("curr").innerHTML = timestamp;
console.log(timestamp);
}
</script>
</body>
</html>

Why does my Javascript code only calculate my age only on the first click of the submit button only?

I have a java-script code which calculates a person age.
A user will enter his/her identity number in an input field and clicks submit. then the java-script code will calculate their age.
i do not understand why the java-script code does not calculate a different age when i change the identity number.
eg identity number 1: 7810104455082, identity number 2: 8001013355088 and identity number 3: 9502242235086
my html code below:
<input id="IDNumber" type="text" name="idnumber" placeholder="ID number" />
<input onclick="return validateID();" id="submit" type="submit" value="Submit" />
<p id="demo">demo</p> <p id="demo2">demo2</p>
<div id="screen" style="width:600px; height:400px; background-color:gray;"></div>
<button id="display">Display</button>
my javascript code below:
<script>
function validateID() {
var ex = /^(((\d{2}((0[13578]|1[02])(0[1-9]|[12]\d|3[01])|(0[13456789]|1[012])(0[1-9]|[12]\d|30)|02(0[1-9]|1\d|2[0-8])))|([02468][048]|[13579][26])0229))(( |-)(\d{4})( |-)(\d{3})|(\d{7}))/;
var idNumber = document.getElementById("IDNumber").value;
if (ex.test(idNumber) == false) {
// alert code goes here
document.getElementById("demo").innerHTML = "Please supply a valid ID number" ;
alert('Please supply a valid ID number');
return false;
}
//Pull out Year and Month and Day for IDNumber
var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
var id_date = tempDate.getDate();
var id_month = tempDate.getMonth();
var id_year = tempDate.getFullYear();
// set variable of fullDate to insert in math calculation
var fullDate = id_year + "/" + (id_month + 1) + "/" + id_date;
//math time calculation to give mil and convert to years
var d1 = new Date(); //"now"
var d2 = new Date(fullDate) // some date
var diff = Math.abs(d1-d2); // difference in milliseconds
var yeardiff = diff / 31536000000;
document.getElementById("demo").innerHTML = "The Age is " + Math.round(yeardiff);
}
</script>
Remove the return on your onclick
<input onclick="validateID();" id="submit" type="submit" value="Submit" />

How to insert the value of javascript into html [duplicate]

This question already has answers here:
How to Add Two Days from Current Date to the Value of a Hidden Input
(3 answers)
How to insert Javascript variables into a database
(1 answer)
Closed 5 years ago.
I want to get the javascript value into my html input value and insert it into the database after the user click the submit
<script>
var currentDate = new Date();
if (currentDate.getDay() == 5) {
var numberOfDaysToAdd = 4; //Adding 4 to skip sat. & sun. if Friday
} else {
var numberOfDaysToAdd = 2; //Adding 2 days if not Friday
}
currentDate.setDate(currentDate.getDate() + numberOfDaysToAdd);
var dd = currentDate.getDate();
var mm = currentDate.getMonth() + 1;
var y = currentDate.getFullYear();
var someFormattedDate = y + '-' + mm + '-' + dd;
document.getElementById("display").innerHTML = someFormattedDate;
</script>
<?php
echo $_GET['someFormattedDate'];
?>
<input type="text" class="w8em format-y-m-d highlight-days-67 range-low-today" name="due_date" id="sd" maxlength="10" value="<?php echo " someFormattedDate " style="border: 3px double #CCCCCC; " disabled/>
Since your input id is sd,
document.getElementById("sd").value = someFormattedDate;
Note: Elements with Disabled attribute are not submitted, enable it before submit.
Full Code:
<?php
echo $_GET['due_date'];
?>
<form name="myform" id="myform" method="GET">
<input type="text" class="w8em format-y-m-d highlight-days-67 range-low-today" name="due_date" id="sd" maxlength="10" style="border: 3px double #CCCCCC; " readonly/>
<input type="submit" name="btn_submit" value="Submit">
</form>
<script>
var currentDate = new Date();
if (currentDate.getDay() == 5) {
var numberOfDaysToAdd = 4; //Adding 4 to skip sat. & sun. if Friday
} else {
var numberOfDaysToAdd = 2; //Adding 2 days if not Friday
}
currentDate.setDate(currentDate.getDate() + numberOfDaysToAdd);
var dd = currentDate.getDate();
var mm = currentDate.getMonth() + 1;
var y = currentDate.getFullYear();
var someFormattedDate = y + '-' + mm + '-' + dd;
document.getElementById("sd").value = someFormattedDate;
</script>
First, put the JavaScript code after the input you want to use. That way the input exists on the page when the code executes.
Second, use the actual id of the input.
Third, set the .value property.
Fourth, put the input in a form.
Fifth, don't disable the input.
Something like this:
<form>
<input type="text" class="w8em format-y-m-d highlight-days-67 range-low-today" name="due_date" id="sd" maxlength="10" style="border: 3px double #CCCCCC;" disabled/>
<input type="submit" value="Submit" />
</form>
<script>
// The rest of your JavaScript code, formatting your date value
document.getElementById("sd").value= someFormattedDate;
</script>
Unless otherwise specified, this <form> will submit a GET request to the current URL by default when the submit button is clicked.
Aside from that it's not really clear to me what you're trying to do with the PHP code here. Why you're trying to output a value that hasn't been submitted yet, or output a literal string, or whatever you're attempting.
<script>
var currentDate = new Date();
if (currentDate.getDay() == 5) {
var numberOfDaysToAdd = 4; //Adding 4 to skip sat. & sun. if Friday
} else {
var numberOfDaysToAdd = 2; //Adding 2 days if not Friday
}
currentDate.setDate(currentDate.getDate() + numberOfDaysToAdd);
var dd = currentDate.getDate();
var mm = currentDate.getMonth() + 1;
var y = currentDate.getFullYear();
var someFormattedDate = y + '-' + mm + '-' + dd;
document.getElementById("sd").innerHTML = someFormattedDate;
</script>
Description:- You are binding data with wrong element.

Increment Serial Numbers and calculate - javascript

Our company has a client that requires a specific checksum on their bar codes. I've come up with the following which allows the user to enter the distributor part number, our part number and our serial number. Right now, when you click save, it will calculate correctly for the bar code with the checksum. NOW, we have added a quantity box so that we can print x number of barcodes with our serial number incrementing by 1. (i.e. 1st serial number is 000001, next will be 000002 and so on). What I've been trying to do for the last week is alter this code so the user can input the part numbers and sn, and it will calculate each bar code up to the quantity.
This is what we would like to have:
If user enters part numbers, first serial number and quantity then clicks "Save" this should be the result. At present, this can only be achieved by entering each serial number and clicking save
*note: while the quantity can be entered, the actual value has not been used in my code...yet
So, to achieve this, I need to find a way to increment the serial numbers without dropping off the leading zeros but maintaining the length of qty.length.
I also need to figure out how to loop each new serial number through with part numbers to get the correct checksum for the bar code. After a week of staring at this, I'm hoping some fresh and experienced eyes can assist. Here is my code.
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Capture Form Fields to CSV</title>
<script type="text/javascript">
<!--
function saveValues() {
var frm = document.form1;
var str = frm.text1.value + frm.text2.value + frm.text3.value;
var dpn = frm.text1.value;
var wpn = frm.text2.value;
var wsn = frm.text3.value;
var strArray = str.split("");
var calcArray = strArray;
var total =0;
for (var i = 0; i < str.length; i++)
strArray[i] = strArray[i].charCodeAt(0);
for (var i = 0; i < strArray.length; i++){
if (strArray[i] >= 65 && strArray[i] <= 90){
calcArray[i] = (strArray[i] - 64) * (i+1)
}
else if (strArray[i] >=97 && strArray[i] <=122) {
calcArray[i] = (strArray[i] - 96) * (i+1)
}
else if (strArray[i] >=48 && strArray[i] <=57) {
calcArray[i] = (strArray[i] - 48) * (i+1)
}
else {
calcArray[i] = 1 * (i+1)
}
}
for (var i in calcArray){
total += calcArray[i];}
var mod2 = str.length - (2*(Math.floor(str.length/2)));
var mod10 = (total + mod2) - (10*(Math.floor((total + mod2)/10))) ;
var chk = mod10;
var record = ""
+ dpn + "," + wpn + "," + wsn + "," +dpn + "~" + wpn + "~" + wsn + "~" + chk + "\n";
frm.textarea1.value += record;
}
function clearText() {
document.form1.textarea1.value = "";P
form1.text1.value = "";
form1.text2.value = "";
form1.text3.value = "";
}
function csvSave() {
var a = document.createElement('a');
with (a) {
href='data:text/csv;base64,' + btoa(document.getElementById('textarea1').value);
download='csvfile.csv';
}
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
//-->
</script>
</head>
<body>
<h1>Capture Form Fields to CSV</h1>
<form name="form1" >
<p>
Distributor Part Number: <input name="text1" type="text" value="GDM1301" /><br />
Our Part Number: <input name="text2" type="text" value="PCBDM160"/><br />
Our Serial Number: <input name="text3" type="text" value="000001"/><br />
Label Quantity: <input name="qty" type="text" value="3"/>
</p>
<p>
<input name="save" type="button" value="Save"
onclick="saveValues(); return false"/>
 
<input name="clear" type="button" value="Clear"
onclick="clearText(); return false"/>
<button onclick="csvSave()">CSV</button>
</p>
<p>
<i>Click 'Save' to add content</i><br />
<textarea id="textarea1" cols="80" rows="20"></textarea>
</p>
</form>
</body>
</html>

Radio button to javascript

I current have a form using radio buttons to choose an item. what I want to do is based on which radio button that is selected add a certain number of days to today's current date. I am unsure of a way to do this but my current idea was to use a IF statement to compare which button is selected and if it is than add a number to the getDate() value. I am currently working on line 42/43. This is my code so far:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Digital Photos</title>
</head>
<body>
Web Program Homepage<br>
ITWP Course Homepage
<p>
<form>
Select the type of item you want to order:
<br>
<input type="radio" name="order" onclick="check(this.value)" value="Hard-Copy Print">Hard-Copy Print<br>
<input type="radio" name="order" onclick="check(this.value)" value="Poster">Poster<br>
<input type="radio" name="order" onclick="check(this.value)" value="Coffee Mug">Coffee Mug<br>
<input type="radio" name="order" onclick="check(this.value)" value="T-Shirt">T-Shirt<br>
<br>
You are ordering a: <input type="text" id="answer" size="20">
</form>
<script type="text/javascript">
/* <![CDATA[ */
function check(order){
document.getElementById("answer").value=order;
}
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = mm+'/'+dd+'/'+yyyy;
document.write("Todays date is " + today);
if
document.write(". Your order will be ready on " + today);
/* ]]> */
</script>
<p></p>
HTML5 Validation
</body>
</html>
Ok, I can see that this is perhaps an assignment - but I for one learn best by example. That said, you need to look over the code and understand it (or else you will never really get good at programming).
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Digital Photos</title>
</head>
<body>
Web Program Homepage<br>
ITWP Course Homepage
<form>
Select the type of item you want to order:
<br>
<div onchange="check()">
<input type="radio" name="order" value="Hard-Copy Print">Hard-Copy Print<br>
<input type="radio" name="order" value="Poster">Poster<br>
<input type="radio" name="order" value="Coffee Mug">Coffee Mug<br>
<input type="radio" name="order" value="T-Shirt">T-Shirt<br>
<br>
</div>
</form>
<div id="orderDetails"></div>
<script type="text/javascript">
/* <![CDATA[ */
function check() {
var nodeList = document.getElementsByName("order");
var value;
for (var i = 0; i < nodeList.length; i++)
{
if(nodeList[i].checked)
{
value = nodeList[i].value;
break;
}
}
var today = new Date();
var arrival = new Date();
if (value == "Hard-Copy Print")
{
//If this one is selected, shipment arrive at current time + 1 day
arrival.setDate(today.getDate() + 1)
}
else if (value == "Poster")
{
//If this one is selected, shipment arrive at current time + 2 days
arrival.setDate(today.getDate() + 2)
}
else if (value == "Coffee Mug")
{
//If this one is selected, shipment arrive at current time + 3 days
arrival.setDate(today.getDate() + 3)
}
else if (value == "T-Shirt")
{
//If this one is selected, shipment arrive at current time + 4 days
arrival.setDate(today.getDate() + 4)
}
else
{
alert("Something went really really reeeeeeeeealy wrong :)");
}
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
var dd2 = arrival.getDate();
var mm2 = arrival.getMonth() + 1; //January is 0!
var yyyy2 = arrival.getFullYear();
if (dd2 < 10) {
dd2 = '0' + dd2
}
if (mm2 < 10) {
mm2 = '0' + mm2
}
today = mm + '/' + dd + '/' + yyyy;
arrival = mm2 + '/' + dd2 + '/' + yyyy2;
var details = "You are ordering: " + value + "<br/><br/> Todays date is " + today + "<br/><br/>" + "Your order will be ready on " + arrival;
document.getElementById("orderDetails").innerHTML = details;
}
</script>
<p></p>
HTML5 Validation
My approach would be to have the radio values as strings that could be used as keys in an array:
<input type="radio" name="order" onclick="check(this.value)" value="hard_copy_print">Hard-Copy Print<br>
<input type="radio" name="order" onclick="check(this.value)" value="poster">Poster<br>
<input type="radio" name="order" onclick="check(this.value)" value="coffee_mug">Coffee Mug<br>
<input type="radio" name="order" onclick="check(this.value)" value="t_shirt">T-Shirt<br>
Then have a keyed array storing the order times for each item:
var orderTimes = array('hard_copy_print' => 4, 'poster' => 2, 'coffee_mug' => 6, 't_shirt' => 8);
Then use the value of the radio item to get the order time.

Categories

Resources