Retrieving a value from a dropdown menu using PHP - javascript

I'm creating an appointment form. I'm trying to retrieve the hour and minute using $_POST['minute'] but I kept getting "Undefined variable or index".
HTML
<form id="theForm" method="POST" onsubmit="ajaxSubmit(); return false">
<h5>Schedule your 15 minute consultation</h5>
<p id="date">MM/DD/YYYY</p>
<div id="time">
<select id="hours" name="hour"></select>
<span>:</span>
<select id="minutes" name="minute"></select>
<div id="timeLabel">
<label class="ampm" name="am" id="am">AM</label> / <label class="ampm" name="pm" id="pm">PM</label>
</div>
</div>
<input placeholder="Name" name="name" id="name" />
<input placeholder="Email" name="email" id="email" />
<button class="submitBtn" name="submitBtn">SUBMIT</button>
<p id="isSent"></p>
</form>
JS
const hours = document.getElementById("hours");
for (let i = 1; i <= 12; i++) {
hours.innerHTML += `<option value="${i}">${i}</option>`;
}
const minutes = document.getElementById("minutes");
for(let i = 0; i <= 45; i+=15) {
if(i < 10) {
minutes.innerHTML += `<option value="0${i}">0${i}</option>`;
} else {
minutes.innerHTML += `<option value="${i}">${i}</option>`;
}
}
function ajaxSubmit() {
let name = document.getElementById('name'),
email = document.getElementById('email'),
date = document.getElementById('date'),
hours = document.getElementById('hours'),
minutes = document.getElementById('minutes'),
am = document.getElementById('am'),
pm = document.getElementById('pm');
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.status == 200 && xhr.readyState == 4) {
document.querySelector("#isSent").innerHTML = xhr.responseText;
}
}
xhr.open('POST', 'mail.php?', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("name=" + name.value +
"&email=" + email.value +
"&date=" + date.value +
"&hours=" + hours.value +
"&minutes=" + minutes.value +
"&am" + am.value +
"&pm" + pm.value);
}
I've tried $hour = $_POST['hour']; but that did not work, same with the minute. So here's my PHP
$hour = null;
$minute = null;
if(isset($_POST['hour'])) {
$hour = $_POST['hour'];
}
if(isset($_POST['minute'])) {
$minute = $_POST['minute'];
}

The issue is the way you are sending form data to PHP. Better way of doing is to use new FormData() function of Javascript. It sends the serialized data so no additional processing is needed.
const hours = document.getElementById("hours");
for (let i = 1; i <= 12; i++) {
hours.innerHTML += `<option value="${i}">${i}</option>`;
}
const minutes = document.getElementById("minutes");
for (let i = 0; i <= 45; i += 15) {
if (i < 10) {
minutes.innerHTML += `<option value="0${i}">0${i}</option>`;
} else {
minutes.innerHTML += `<option value="${i}">${i}</option>`;
}
}
function ajaxSubmit() {
var form = document.querySelector('form');
var data = Object.fromEntries(new FormData(form));
console.log(data)
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.status == 200 && xhr.readyState == 4) {
document.querySelector("#isSent").innerHTML = xhr.responseText;
}
}
xhr.open('POST', 'mail.php?', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
}
<form id="theForm" method="POST" onsubmit="ajaxSubmit(); return false">
<h5>Schedule your 15 minute consultation</h5>
<p id="date">MM/DD/YYYY</p>
<div id="time">
<select id="hours" name="hour"></select> <span>:</span>
<select id="minutes" name="minute"></select>
<div id="timeLabel">
<label class="ampm" name="am" id="am">AM</label> / <label class="ampm" name="pm" id="pm">PM</label>
</div>
</div>
<input placeholder="Name" name="name" id="name" />
<input placeholder="Email" name="email" id="email" />
<button class="submitBtn" name="submitBtn">SUBMIT</button>
<p id="isSent"></p>
</form>

Change your $_POST from hour to plural hours, the same with minute to minutes.
$hours = null;
$minute = null;
if(isset($_POST['hours'])) {
$hours = $_POST['hours'];
}
if(isset($_POST['minutes'])) {
$minutes = $_POST['minutes'];
}
//this message will display on #isSent paragraph
if(isset($hours) and isset($minutes))
echo "your Schedule 15 minute consultation($hours:$minutes) has been registered!";
Tip: for javascript generating readable time format use padStart function:
for(let i = 0; i <= 45; i+=15) {
minutes.innerHTML += `<option value="${(''+i).padStart(2,'0')}">${(''+i).padStart(2,'0')}</option>`;
}
Insead of if else statement condition.
for(let i = 0; i <= 45; i+=15) {
if(i < 10) {
minutes.innerHTML += `<option value="0${i}">0${i}</option>`;
} else {
minutes.innerHTML += `<option value="${i}">${i}</option>`;
}
}

Related

How to get out the date validation to another separate function

I want to take out the date validation(a validation to my code to validate year between 1930 and the current year and if it's not correct it should print an error) to another separate new function, Instead of the Addmovie function.
i want to make another new function called datevalidation and I want to add date validation, which is currently in the addmovie function.
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Week 07 Pass Submission</title>
<script src="./w7p.js"></script>
</head>
<body>
<header>
<h1>Week 07 Pass Submission</h1>
</header>
<article>
<form>
<label for="movie">Movie title</label>
<input type="text" id="movie" /><br /><br />
<span id="yearValidation" style="color: red"></span>
<br />
<label for="year">Release year</label>
<input type="text" id="year" /><br /><br />
<input type="button" id="add" value="Add">
<input type="button" id="show" value="List All">
</form><br />
<div style="padding-left: 20px;" id="list"></div>
</article>
</body>
</html>
JavaScript Code
var movieTitle = [];
var movieReleaseYear = [];
function init() {
var add = document.getElementById('add');
add.onclick = () => addMovie(2022);
var show = document.getElementById('show');
show.onclick = () => displayData();
}
function addMovie(currentYear) {
var name = document.getElementById('movie');
var year = document.getElementById('year');
var year = document.getElementById('year').value;
if (year <= 1930 || year >= currentYear) {
document.getElementById('yearValidation').innerHTML = 'Error';
} else {
document.getElementById('yearValidation').innerHTML = '';
}
movieTitle.push(name.value);
movieReleaseYear.push(year.value);
}
function displayData() {
if (movieTitle.length == 0) {
document.getElementById('list').innerHTML = 'there is no data';
} else {
var output = '';
movieTitle.forEach(
(element, index) =>
(output +=
' ' +
(index + 1) +
'. ' +
element +
'\t\t' +
movieReleaseYear[index] +
'<br />')
);
document.getElementById('list').innerHTML = output;
}
}
window.onload = init;
You can declare a separate function dateValidation() and call it inside addMovie()
var movieTitle = [];
var movieReleaseYear = [];
function init() {
var add = document.getElementById('add');
add.onclick = () => addMovie(2022);
var show = document.getElementById('show');
show.onclick = () => displayData();
}
function dateValidation(year,currentYear){
if (year <= 1930 || year >= currentYear) {
document.getElementById('yearValidation').innerHTML = 'Error';
}
movieTitle.push(name.value);
movieReleaseYear.push(year.value);
}
function addMovie(currentYear) {
var name = document.getElementById('movie');
var year = document.getElementById('year').value;
dateValidation(year,currentYear);
}
function displayData() {
if (movieTitle.length == 0) {
document.getElementById('list').innerHTML = 'there is no data';
} else {
var output = '';
movieTitle.forEach(
(element, index) =>
(output +=
' ' +
(index + 1) +
'. ' +
element +
'\t\t' +
movieReleaseYear[index] +
'<br />')
);
document.getElementById('list').innerHTML = output;
}
}
window.onload = init;

NaN in result variable and calculation

I have been studying JavaScript and experiment with some things. I have build a small application (see code below). Everything is going well untill the function eindResultaat(). Here it seems that there is something with resultaat3 (it is NaN) but I can not figure out why. resultaat1 and resultaat2 are getting processed in the same way and there it goes fine.
var resultatenArray = [];
var eindcijfer, eRes1, eRes2, eRes3, resultaat1, resultaat2, resultaat3;
function berekening1() {
resultaat1 = document.getElementById("eersteTentamen").value;
console.log("Dit is resultaat1 " + resultaat1);
if ((resultaat1 == "GR") || (resultaat1 == "gr")) {
document.getElementById("res1").innerHTML = "Geen resultaat";
resultaat1 = resultaat1 || 0;
//eRes1 = 0.0;
} else {
let res1 = document.getElementById("res1");
res1.innerHTML = resultaat1;
res1.style.color = resultaat1 >= 5.5 ? 'green' : 'red';
document.getElementById("res1").innerHTML = resultaat1;
//eRes1 = resultaat1;
resultatenArray.push(resultaat1);
console.log(resultatenArray);
}
}
function berekening2() {
resultaat2 = document.getElementById("tweedeTentamen").value;
console.log("Dit is resultaat2 " + resultaat2);
if ((resultaat2 == "GR") || (resultaat2 == "gr")) {
document.getElementById("res2").innerHTML = "Geen resultaat";
eRes2 = 0.0;
} else {
let res2 = document.getElementById("res2");
res2.innerHTML = resultaat2;
res2.style.color = resultaat2 >= 5.5 ? 'green' : 'red';
document.getElementById("res2").innerHTML = resultaat2;
//eRes2 = resultaat2;
resultatenArray.push(resultaat2);
console.log(resultatenArray);
}
}
function berekening3() {
resultaat3 = document.getElementById("derdeTentamen").value;
console.log("Dit is resultaat3 " + resultaat3);
if ((resultaat3 == "GR") || (resultaat3 == "gr")) {
document.getElementById("res3").innerHTML = "Geen resultaat";
var resultaat3 = 0.0;
//eRes3 = 0;
console.log(resultaat3);
} else {
let res3 = document.getElementById("res3");
res3.innerHTML = resultaat3;
res3.style.color = resultaat3 >= 5.5 ? 'green' : 'red';
document.getElementById("res3").innerHTML = resultaat3;
//eRes3 = resultaat3;
resultatenArray.push(resultaat3);
console.log(resultatenArray);
}
console.log(isNaN(resultaat3));
}
function eindResultaat() {
var aantalDeelTentamens = resultatenArray.length;
console.log(aantalDeelTentamens);
console.log("resultaten: " + resultaat1, resultaat2, resultaat3);
//console.log("eRes resultaten:" + eRes1, eRes2, eRes3);
//parseFloat(resultaat1);
//parseFloat(resultaat2);
//parseFloat(resultaat3);
console.log(isNaN(resultaat1));
console.log(isNaN(resultaat2));
console.log(isNaN(resultaat3));
eindcijfer = ((resultaat1 + resultaat2 + resultaat3) / aantalDeelTentamens).toFixed(1);
//var eindcijfer = ((eRes1 + eRes2 + eRes3)/aantalDeelTentamens).toFixed(1);
console.log(eindcijfer);
console.log(isNaN(eindcijfer));
document.getElementById("eindresultaat").innerHTML = eindcijfer;
}
Resultaat <b>eerste</b> deeltentamen: <input type="text" value="" id="eersteTentamen"><input type="submit" name=buttonResultaat1 value="Resultaat bevestigen" onclick="berekening1()"><br><br> Resultaat <b>tweede</b> deeltentamen: <input type="text" value=""
id="tweedeTentamen"><input type="submit" name=buttonResultaat2 value="Resultaat bevestigen" onclick="berekening2()"><br><br> Resultaat <b>derde</b> deeltentamen: <input type="text" value="" id="derdeTentamen"><input type="submit" name=buttonResultaat3
value="Resultaat bevestigen" onclick="berekening3()"><br><br>
<hr> Resultaat <b>eerste</b> deeltentamen: <span id="res1"></span><br> Resultaat <b>tweede</b> deeltentamen: <span id="res2"></span><br> Resultaat <b>derde</b> deeltentamen: <span id="res3"></span><br><br>
<hr>
<br>
<input type="submit" name=eindresultaat value="Bereken eindresultaat" onclick="eindResultaat()"><br><br>
<b>Het eindresultaat is: </b> <span id="eindresultaat"></span>
Indeed, it was deleting the var at some places so the code works. No I am busy with what to do if someone makes 2 test in stead of 3. So the average must be calculated over 2 tests.

Firestore document pages

I'm trying to make an HTML table that lists the names of people in my firestore database then when clicked on their row comes up with a page where it contains some information and then gives me the option to upload some new information about them.
It works for until I upload the set of data than when I click on the other pages it doesn't load any data. I'm sorry in advance, its a lot of code to look through because i don't know where the problem is.
<div class="URP_div" id="URP" style="display: none;">
<h1 id="StudentPage"></h1>
<div class="SPROW">
<labe>Name:</label>
<label id="SName"></label>
</div>
<div class="SPROW">
<label for="">IRL:</label>
<label id="SId"></label>
</div>
<div class="SPROW">
<label for="">Session Date:</label>
<label for="" id="SSd"></label>
</div>
<div class="SPROW">
<label for="">Exam Level:</label>
<label for="" id="SEl"></label>
</div>
<div class="SPROW">
<label for="">Exam Genre:</label>
<label for="" id="SEg"></label>
</div>
<div class="SPROW">
<label for="">Teacher ID:</label>
<label for="" id="STId"></label>
</div>
<div id="AGR">
<div class="ExaminerArea-Results1">
<label>Accredited Grade Results</label>
<input type="number" placeholder="Technique: (15)" id="Res1" class="Results-input">
<input type="number" placeholder="Control: (15)" id="Res2" class="Results-input">
<input type="number" placeholder="Stanima & Agility: (15)" id="Res3" class="Results-input">
<input type="number" placeholder="Musicality: (15)" id="Res4" class="Results-input">
<input type="number" placeholder="Interpretation: (10)" id="Res5" class="Results-input">
</div>
<div class="ExaminerArea-Results2">
<input type="number" placeholder="Knowledge: (15)" id="Res6" class="Results-input">
<input type="number" placeholder="Performance Skills: (5)" id="Res7" class="Results-input">
<input type="number" placeholder="Personal Discipline: (10)" id="Res8" class="Results-input">
</div>
</div>
<div id="NAGR">
<div class="FSPO">
<label>Foundation/Street/Performance Only</label>
<select name="FSPO" id="RPMD">
<option value="Not Awarded" selected="">Not Awarded</option>
<option value="Pass">Pass</option>
<option value="Merit">Merit</option>
<option value="Distingtion">Distinction</option>
</select>
</div>
</div>
<div class="SPROW">
<textarea name="ResultsComment" id="RC" cols="30" rows="10" placeholder="Exam Comments...."
maxlength="200"></textarea>
</div>
<button onclick="SumbitResult()">Upload</button>
<button onclick="BURP()">Back</button>
<button onclick="logout()">Logout</button>
</div>
function BURP() {
document.getElementById('URP').style.display = "none";
document.getElementById('exam').style.display = "block";
document.getElementById('SName').innerHTML = "";
document.getElementById('SId').innerHTML = "";
document.getElementById('SSd').innerHTML = "";
document.getElementById('SEl').innerHTML = "";
document.getElementById('SEg').innerHTML = "";
document.getElementById('STId').innerHTML = "";
document.getElementById('StudentPage').innerHTML = "";
var table = document.getElementById('StduentTable')
for (var i = table.rows.length - 1; i > 0; i--) {
table.deleteRow(i);
}
var db = firebase.firestore();
console.log(CRSD);
db.collection("Students").where('SessionDate', '==', CRSD).where('TeacherID', '==', CRTID).onSnapshot(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
var data = doc.data();
var content = '';
content += '<tr>';
content += '<td id="name">' + data.Student + '</td>';
content += '<td id="id">' + data.StudentID + '</td>';
content += '<td id="eg">' + data.ExamGenre + '</td>';
content += '<td id="el">' + data.ExamLevel + '</td>';
content += '<td>' + '<button class="btn" onclick="URP()">Upload Results</button>' + '</td>';
$('#StduentTable').append(content);
})
});
}
var cel1;
var cel2;
var cel3;
var cel4;
$('#StduentTable').on('click', '.btn', function () {
var currow = $(this).closest('tr');
cel1 = currow.find('td:eq(0)').text();
cel2 = currow.find('td:eq(1)').text();
cel3 = currow.find('td:eq(2)').text();
cel4 = currow.find('td:eq(3)').text();
console.log(cel1)
console.log(cel2)
console.log(cel3)
console.log(cel4)
var table = document.getElementById("StduentTable");
var CRSD = document.getElementById('RSD').value;
var CRTID = document.getElementById('RTID').value;
document.getElementById('URP').style.display = "block";
document.getElementById('exam').style.display = "none";
var db = firebase.firestore();
db.collection("Students").where('SessionDate', '==', CRSD).where('TeacherID', '==', CRTID).where('Student', '==', cel1).where('StudentID', '==', cel2).where('ExamLevel', '==', cel4).where('ExamGenre', '==', cel3).onSnapshot(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
console.log('test');
var data = doc.data();
var text = data.Student + "'s Page.";
DS = data.Student;
DSID = data.StudentID;
DSSD = data.SessionDate;
DSEL = data.ExamLevel;
DSEG = data.ExamGenre;
DSTID = data.TeacherID;
document.getElementById('StudentPage').innerHTML = text;
document.getElementById('SName').innerHTML = DS;
document.getElementById('SId').innerHTML = DSID;
document.getElementById('SSd').innerHTML = DSSD;
document.getElementById('SEl').innerHTML = DSEL;
document.getElementById('SEg').innerHTML = DSEG;
document.getElementById('STId').innerHTML = DSTID;
})
});
})
<script>
function SumbitResult() {
var CRSD = document.getElementById('RSD').value;
var CRTID = document.getElementById('RTID').value;
var dataIn = false
var db = firebase.firestore();
var r1 = document.getElementById('Res1').value;
var r2 = document.getElementById('Res2').value;
var r3 = document.getElementById('Res3').value;
var r4 = document.getElementById('Res4').value;
var r5 = document.getElementById('Res5').value;
var r6 = document.getElementById('Res6').value;
var r7 = document.getElementById('Res7').value;
var r8 = document.getElementById('Res8').value;
var ExamComment = document.getElementById('RC').value;
var NAW = document.getElementById('RPMD').value;
var totalscore =
document.getElementById('Res1').valueAsNumber +
document.getElementById('Res2').valueAsNumber +
document.getElementById('Res3').valueAsNumber +
document.getElementById('Res4').valueAsNumber +
document.getElementById('Res5').valueAsNumber +
document.getElementById('Res6').valueAsNumber +
document.getElementById('Res7').valueAsNumber +
document.getElementById('Res8').valueAsNumber;
var tot2 = totalscore;
if (NAW !== "Not Awarded") {
r1 = 0;
r2 = 0;
r3 = 0;
r4 = 0;
r5 = 0;
r6 = 0;
r7 = 0;
r8 = 0;
r9 = 0;
r10 = 0;
tot2 = 0;
}
var OverallResult;
if (tot2 > 89) {
OverallResult = "Distingtion with Honours"
}
if (tot2 > 76 && tot2 < 88) {
OverallResult = "Distingtion"
}
if (tot2 > 58 && tot2 < 75) {
OverallResult = "Merit"
}
if (tot2 > 43 && tot2 < 57) {
OverallResult = "Pass"
}
if (tot2 <= 42) {
OverallResult = "Not Awared"
}
db.collection("Students").where("SessionDate", "==", CRSD)
.where('SessionDate', '==', CRSD).where('TeacherID', '==', CRTID).where('Student', '==', cel1).where('StudentID', '==', cel2).where('ExamLevel', '==', cel4).where('ExamGenre', '==', cel3)
.onSnapshot(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
db.collection("Students").doc(doc.id).update({
"Results.Results1": r1,
"Results.Results2": r2,
"Results.Results3": r3,
"Results.Results4": r4,
"Results.Results5": r5,
"Results.Results6": r6,
"Results.Results7": r7,
"Results.Results8": r8,
"Results.TotalScore": tot2,
"Results.Exam_Comments": ExamComment,
"Results.Non_Accredited_Exam": NAW,
"Results.Examiner_ID": DBID,
"Results.Overall_Results": OverallResult
})
dataIn = true;
})
});
if (dataIn = true) {
document.getElementById('REG').value = "";
document.getElementById('REL').value = "";
document.getElementById('RSD').value = "";
document.getElementById('RCID').value = "";
document.getElementById('RTID').value = "";
document.getElementById('RC').value = "";
document.getElementById('Res1').value = "";
document.getElementById('Res2').value = "";
document.getElementById('Res3').value = "";
document.getElementById('Res4').value = "";
document.getElementById('Res5').value = "";
document.getElementById('Res6').value = "";
document.getElementById('Res7').value = "";
document.getElementById('Res8').value = "";
}
}
</script>

Auto populate form field with javascript

Sorry for such a noob problem - I've not found a solution after browsing many posts and I'm afraid I don't even know what question to ask - I'm trying to auto populate the 'sunits' input field to the value of the 'bunits' input, unless changed. I barely cobbled this together for some friends, and do apologize for the poor style and everything else. The code below is also the homepage at http://lootsim.com :
<div id="buyformdiv" class="fluid ">
<span id="pickingupspan" class="actionspan">Buying:</span>
<p># units to be bought:
<input id="bunits" type="number" step="1" onchange="update()"></p>
<p>
Cost per unit :
<input id="cunits" type="number" step="0.01" onchange="update()"></p>
<p>
Overhead :
<input id="cxbship" type="number" step="0.01" onchange="update()"></p>
</div>
<div id="sellformdiv" class="fluid ">
<span id="gettingridspan" class="actionspan">Selling:</span>
<p># units to be sold:
<input id="sunits" type="number" step="1" onchange="update()"></p>
<p>
selling for ($ each) :
<input id="sprice" type="number" step="0.01" onchange="update()"></p>
<p>
Frequency :
<select id="sfreq" onchange="update()">
<option value="1">Once</option>
<option value="7">Week</option>
<option value="31">Month (31 days)</option>
<option value="365">Year</option>
</select>
</p>
</div>
Javascript"
var bunits, cunits, cxb, cxbship, btotal, sunits, sfreq, sprice, net, profit;
function update() {
var bunits = document.getElementById('bunits').value;
var cunits = document.getElementById('cunits').value;
var cunits = parseFloat(cunits).toFixed(2);
var cxbship = document.getElementById('cxbship').value;
var cxbship = parseFloat(cxbship).toFixed(2);
var cxb = bunits * cunits;
var cxb = parseFloat(cxb).toFixed(2);
var btotal = parseFloat(cxb) + parseFloat(cxbship);
var btotal = parseFloat(btotal).toFixed(2);
var sunits = document.getElementById('sunits').value;
var sprice = document.getElementById('sprice').value;
var sprice = parseFloat(sprice).toFixed(2);
var sfreq = document.getElementById('sfreq').value;
var sunitxp = sunits * sprice;
var sunitxp = parseFloat(sunitxp).toFixed(2);
var salesxdays = sunitxp * sfreq;
var salesxdays = parseFloat(salesxdays).toFixed(2);
//populate numbers in results window
if (bunits > 0) {
document.getElementById('bunitsspan').innerHTML = "Buying " + bunits + " units";
document.getElementById('sunits').value = bunits;
}
if (cunits > 0) {
document.getElementById('costspan').innerHTML = "at $" + cunits + " per unit";
}
if (cxb > 0) {
document.getElementById('cxbspan').innerHTML = "Subtotal: $" + cxb;
}
if (cxbship > 0) {
document.getElementById('cxbshipspan').innerHTML = "Overhead: " + cxbship;
}
if (btotal > 0) {
document.getElementById('subtotalspan').innerHTML = "<b>Total: $" + btotal + "</b>";
}
//populate income in results span
if (sunits > 0) {
document.getElementById('sunitsspan').innerHTML = "Selling " + sunits + " units";
}
if (sprice > 0) {
document.getElementById('sellcostspan').innerHTML = "for $" + sprice + " each";
}
if (sunitxp > 0) {
document.getElementById('sunitxpspan').innerHTML = "Subtotal: $" + sunitxp;
}
if (sfreq > 0 ) {
if ((sfreq == 1) && (sprice > 0)){
document.getElementById('sellfreqspan').innerHTML = "all units";
} else if (sfreq == 7) {
document.getElementById('sellfreqspan').innerHTML = "every day for a week";
} else if (sfreq == 31) {
document.getElementById('sellfreqspan').innerHTML = "every day for a month";
} else if (sfreq == 365) {
document.getElementById('sellfreqspan').innerHTML = "every day for a year";
}
}
if (salesxdays > 0) {
document.getElementById('salesxdays').innerHTML = "Total: $" + salesxdays;
}
}

How to put Stop and Reset button in html and javascript

I need help,
How to put Stop and Reset button in html and javascript
Here my countdown javascript and html code and also put chrome notifications with sound,
sounds loop notify me left 10 Seconds after countdown then 0 notify me in chrome notification, and also show countdown value in page title
function do_countdown() {
var start_num = document.getElementById("value").value;
var unit_var = document.getElementById("countdown_unit").value;
start_num = start_num * parseInt(unit_var);
var countdown_output = document.getElementById('countdown_div');
if (start_num > 0) {
countdown_output.innerHTML = format_as_time(start_num);
var t=setTimeout("update_clock(\"countdown_div\", "+start_num+")", 1000);
}
return false;
}
function update_clock(countdown_div, new_value) {
var countdown_output = document.getElementById(countdown_div);
var new_value = new_value - 1;
if (new_value > 0) {
new_formatted_value = format_as_time(new_value);
countdown_output.innerHTML = new_formatted_value;
var t=setTimeout("update_clock(\"countdown_div\", "+new_value+")", 1000);
} else {
countdown_output.innerHTML = "Time's UP!";
}
}
function format_as_time(seconds) {
var minutes = parseInt(seconds/60);
var seconds = seconds - (minutes*60);
if (minutes < 10) {
minutes = "0"+minutes;
}
if (seconds < 10) {
seconds = "0"+seconds;
}
var return_var = minutes+':'+seconds;
return return_var;
}
And also html
<form id="countdown_form" onSubmit="return do_countdown();">
Countdown from: <input type="text" style="width: 30px" id="value" value="10" text-align="center"/>
<select id="countdown_unit">
<option value="1">Seconds</option>
<option value="60">Minutes</option>
<option value="3600">Hours</option>
</select>
<input type="submit" value="Start" />
<!--<input type="button" value="Reset" id="reset">-->
</form>
<div id="countdown_div"> </div>
javascript
changes
1.taken window variables t1,t2 where the timers are going to be assigned
2.added a button(name:reset),which on click calls doReset function
3.added doStuff function
window.t1=null;
window.t2=null;
function do_countdown() {
var start_num = document.getElementById("value").value;
var unit_var = document.getElementById("countdown_unit").value;
start_num = start_num * parseInt(unit_var);
var countdown_output = document.getElementById('countdown_div');
if (start_num > 0) {
countdown_output.innerHTML = format_as_time(start_num);
window.t1=setTimeout("update_clock(\"countdown_div\", "+start_num+")", 1000);
}
return false;
}
function update_clock(countdown_div, new_value) {
var countdown_output = document.getElementById(countdown_div);
var new_value = new_value - 1;
if (new_value > 0) {
new_formatted_value = format_as_time(new_value);
countdown_output.innerHTML = new_formatted_value;
window.t2=setTimeout("update_clock(\"countdown_div\", "+new_value+")", 1000);
} else {
countdown_output.innerHTML = "Time's UP!";
}
}
function format_as_time(seconds) {
var minutes = parseInt(seconds/60);
var seconds = seconds - (minutes*60);
if (minutes < 10) {
minutes = "0"+minutes;
}
if (seconds < 10) {
seconds = "0"+seconds;
}
var return_var = minutes+':'+seconds;
return return_var;
}
function doReset(){
window.clearTimeout(window.t1);
window.clearTimeout(window.t2);
document.getElementById('countdown_div').innerHTML="";
}
HTML
<form id="countdown_form" onSubmit="return do_countdown();">
Countdown from: <input type="text" style="width: 30px" id="value" value="10" text-align="center"/>
<select id="countdown_unit">
<option value="1">Seconds</option>
<option value="60">Minutes</option>
<option value="3600">Hours</option>
</select>
<input type="submit" value="Start" />
<input type="button" onClick="return doReset();" value="Reset" id="reset">
</form>
<div id="countdown_div"> </div>
Use the reset attribute in your form to clear the form input values
<input type="reset"value="Reset">
Take a look here http://jsfiddle.net/05y89wn3/14/
you have to clear the timeout ,reset the form and change the html value of the countdown_div
var reset = document.getElementById("reset_button");
var t;
reset.onclick = function() {
clearTimeout(t);
document.getElementById("countdown_form").reset();
document.getElementById("countdown_div").innerHTML="";
}

Categories