I am trying to create a dynamic dropdown field that depends on a previous input field's value. I have a length dropdown with the options, 30 min., 60 min. and 90 min. I also have a startTime and endTime (basically a range) that a user has. I am trying to dynamically add fields to my time dropdown, that increments based on the length chosen. For example, if the startTime is 10:00 am, the endTime is 2:00 pm, and the length is 60 min; I want the dropdown to be created like 10:00 am, 11:00 am, 12:00 pm, 1:00 pm, 2:00 pm. I would appreciate any guidance with doing this efficiently.
JavaScript
var length = document.getElementById('length');
var chosenLength = length.options[length.selectedIndex].value;
var startTime = document.getElementById('start');
var endTime = document.getElementById('end');
var time = document.getElementById('time');
time.disabled = true
function disabled() {
if (chosenLength.value != "") {
time.disabled = false;
}
}
function timeGenerate() {
for (i = startTime; i < endTime; i++) {
time + chosenLength;
}
}
function addDropdown() {
var newDrop = document.createElement('div');
var doc = '<select>',
times = timeGenerate(), i;
for (i = 0; i < times.length; i++) {
doc += "<option value='" + times[i] + "'>" + times[i] + "</option>";
}
doc += '</select>';
newDrop.innerHTML = doc;
document.getElementById(divname).appendChild(newDrop);
}
HTML
<div class="text-center">
<div class="form-group">
<div class="ins-left">
<p>Cello</p>
</div>
<div class="date-right">
<p>May 2, 2019</p>
</div>
</div>
<br />
<br />
<div class="form-group">
<label class="ins-l">Length</label>
<select class="form-control" id="length">
<option>30 min.</option>
<option>60 min.</option>
<option>90 min.</option>
</select>
</div>
<br />
<div class="form-group">
<label>Time</label>
<select class="form-control" id="time">
</select>
</div>
<div class="bottom">
<button type="submit" name="submit" class="btn blue_button">Book Now</button>
</div>
</div>
<div class="hidden">
<p id="start">10:00 am</p>
<p id="end">2:00 pm</p>
</div>
JSFiddle: https://jsfiddle.net/ta5h034L/2/
If you use moment.js I think generate schedule time would be easy for you. I have updated snipped as per your requirement. I think this method would be much helpful for you.
I have updated your snippet, would you please have a look the updated script on JSFiddle,
JSFiddle Updated : https://jsfiddle.net/jeLk4xhs/3/
The main code would be like,
var start = "10:00 AM";
var end = "2:00 PM";
var timeDistance = 30;
var slotTimes = [];
var startMoment = moment(start, "h:mm A");
var endMoment = moment(end, "h:mm A");
while (startMoment.isSameOrBefore(endMoment)) {
slotTimes.push(startMoment.format("h:mm A"));
startMoment = startMoment.add(timeDistance, 'minutes');
}
console.log(slotTimes);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js"></script>
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
</body>
</html>
thank you :)
May this helpful for you !!
<body>
<div>
<label >Length</label>
<select id="length">
<option>30 min.</option>
<option>60 min.</option>
<option>90 min.</option>
</select>
</div>
<div>
<label>Time</label>
<select class="time">
</select>
</div>
<script>
$(document).ready(function(){
$('select').on('change', function() {
var start = 10;
var end = 2;
var options=" ";
var h,m;
switch($("#length").val()){
h = 10;
m = 0;
options += '<option value=" ">'+h:m+'</option>';
case 30:
for(var i=start;i<end;i++){
m = m + $("#length").val();
if(m == 60){
h++;
m=0;
}
options+= '<option value="'+h+'">'+h+":"+m+'</option>';
}
break;
case 60;
for(var i=start;i<end;i++){
m = m + $("#length").val();
if(m == 60){
h++;
m=0;
}
options+= '<option value="'+h+'">'+h+":"+m+'</option>';
}
break;
case 90;
for(var i=start;i<end;i++){
m = m + $("#length").val();
if(m > 60){
h++;
m=30;
}
options+= '<option value="'+h+'">'+h+":"+m+'</option>';
}
break;
}
$('.time').html(options);
});
});
</script>
</body>
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have created a calendar using HTML and Javascript in my calendar I have highlighted some dates in a particular month using Jquery but I want to highlight the multiple dates in all the months. In my calendar months and years are displayed using dropdown list and the dates are displayed using HTML table please give the solution
This is my code
HTML Code
<div class="col-md-3">
<div class="calendar1">
<h3 class="card-header" id="monthAndYear"></h3>
</div>
<head>
<div class="cal">
<form class="form-inline">
<label class="jumpto col-md-4" for="month">Jump To: </label>
<select class="form-control col-md-6" name="month" id="month" onchange="jump()">
<option value=0>Jan</option>
<option value=1>Feb</option>
<option value=2>Mar</option>
<option value=3>Apr</option>
<option value=4>May</option>
<option value=5>Jun</option>
<option value=6>Jul</option>
<option value=7>Aug</option>
<option value=8>Sep</option>
<option value=9>Oct</option>
<option value=10>Nov</option>
<option value=11>Dec</option>
</select>
<div class="col-md-1"></div>
<label for="year"></label><select class="form-control col-md-6" name="year" id="year" onchange="jump()">
<option value=2018>2018</option>
<option value=2019>2019</option>
<option value=2020>2020</option>
<option value=2021>2021</option>
</select></form>
<div id="calendar" >
<table class="table table-bordered table-responsive-md" cellpadding="20" >
<tr bgcolor="white">
<th>Sun</th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
</tr>
<tbody id="calendar-body" style="color:black;" bgcolor="white">
</tbody >
</table>
</div>
<div class="form-inline">
<button class="btn btn-outline-primary col-md-5" id="previous" onclick="previous()">Previous</button>
<div class="col-md-2"></div>
<button class="btn btn-outline-primary col-md-5" id="next" onclick="next()">Next</button>
</div>
<br/>
</head>
</div>
</div>
JavaScript code
<script>
let today = new Date();
let currentMonth = today.getMonth();
let currentYear = today.getFullYear();
let selectYear = document.getElementById("year");
let selectMonth = document.getElementById("month");
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
let monthAndYear = document.getElementById("monthAndYear");
showCalendar(currentMonth, currentYear);
function next() {
currentYear = (currentMonth === 11) ? currentYear + 1 : currentYear;
currentMonth = (currentMonth + 1) % 12;
showCalendar(currentMonth, currentYear);
}
function previous() {
currentYear = (currentMonth === 0) ? currentYear - 1 : currentYear;
currentMonth = (currentMonth === 0) ? 11 : currentMonth - 1;
showCalendar(currentMonth, currentYear);
}
function jump() {
currentYear = parseInt(selectYear.value);
currentMonth = parseInt(selectMonth.value);
showCalendar(currentMonth, currentYear);
}
function showCalendar(month, year) {
let firstDay = (new Date(year, month)).getDay();
let daysInMonth = 32 - new Date(year, month, 32).getDate();
let tbl = document.getElementById("calendar-body"); // body of the calendar
// clearing all previous cells
tbl.innerHTML = "";
// filing data about month and in the page via DOM.
monthAndYear.innerHTML = months[month] + " " + year;
selectYear.value = year;
selectMonth.value = month;
// creating all cells
let date = 1;
for (let i = 0; i < 6; i++) {
// creates a table row
let row = document.createElement("tr");
//creating individual cells, filing them up with data.
for (let j = 0; j < 7; j++) {
if (i === 0 && j < firstDay) {
let cell = document.createElement("td");
let cellText = document.createTextNode("");
cell.appendChild(cellText);
row.appendChild(cell);
}
else if (date > daysInMonth) {
break;
}
else {
let cell = document.createElement("td");
let cellText = document.createTextNode(date);
if (date === today.getDate() && year === today.getFullYear() && month === today.getMonth()) {
cell.classList.add("bg-info");
} // color today's date
cell.appendChild(cellText);
row.appendChild(cell);
date++;
}
}
tbl.appendChild(row); // appending each row into calendar body.
//debugger;
var mnth=[<?php echo $month2; ?>];
//alert(mnth);
mnth=mnth.toString();
mn=mnth.split(',');
mlength=mn.length;
// alert(mlength);
for( var j=1;j< mlength;j++){
var newmn=mn[j];
// alert(newmn);
$('select#month').find('option').each(function() {
var data1=$(this).val();
//alert(data1);
if (data1==newmn){
//alert(data1);
var ary=[<?php echo $value; ?>];
//alert(ary);
ldate=ary.toString();
ldate=ldate.split(',');
// alert(ldate);
llength=ldate.length;
// alert(llength);
for ( var i = 0; i <llength; i++) {
var newdate= ldate[i];
$('#calendar > table > tbody > tr').each(function() {
$(this).children('td').each(function(){
var data = $(this).html();
if (data==newdate)
{
$(this).css("background-color", "green");
}
})
});
}
}
});
}
}
}
</script>
var dates =[2019-12-21,2019-12-22,2019-12-23,2019-12-25,2019-12-26,2019-12-31,2020-01-01,2020-01-02,2019-12-28];
Provide your code and calendar library to giving a better solution for you. Suggest answer for you can start developing...
var dates = ['01/10/2020', '01/20/2020', '01/30/2020'];
$('#date').datepicker({
dateFormat: 'dd/mm/yy',
beforeShowDay: highlightDays
});
function highlightDays(date) {
for (var i = 0; i < dates.length; i++) {
if (new Date(dates[i]).toString() == date.toString()) {
return [true, 'highlight'];
}
}
return [true, ''];
}
td.highlight > a {
background: #F0DC23!important;
}
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="date"></div>
I have a personal time keeper I am putting together for work. We are allotted 50 minutes a week, and I wanted to make a fancy way of keeping track of that time.
I have a method that works:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
#example1 {
background-color="#0CD6C7";
}
</style>
<div id="example2">
<meta charset="utf-8" />
<title> Personal Timer</title>
<script type="text/javascript">
function setTimes(info) {
var sel = info.split('|');
document.getElementById('time1').value = sel[0];
document.getElementById('time2').value = sel[1];
}
</script>
</head>
<body bgcolor="#0CD6C7">
<div id="example1">
<hr align="left" size="0.5" color="white" width="82%">
<br>
<font face="arial">
<input id="time1" value="50:00" size="5"> 50 minutes of personal time per week <br>
<input id="time2" value="ex: 2:36" onfocus="this.value=''" size="5"> Type in the length of your personal break<br>
<button onclick="document.getElementById('time1').value = timeAddSub('time1','time2',false)">Enter</button>
<script type="text/javascript">
// From: http://www.webdeveloper.com/forum/showthread.php?273699-add-2-fields-containing-time-values-in-hh-mm-format&daysprune=30
Number.prototype.padDigit = function() { return (this < 10) ? '0'+this : ''+this; }
function timeAddSub(id1, id2, flag) { // flag=true to add values and flag=false to subtract values
var tt1 = document.getElementById(id1).value; if (tt1 == '') { return ''; }
var t1 = tt1.split(':');
var tt2 = document.getElementById(id2).value; if (tt2 == '') { return ''; }
var t2 = tt2.split(':');
tt1 = Number(t1[0])*60+Number(t1[1]);
tt2 = Number(t2[0])*60+Number(t2[1]);
var diff = 0; if (flag) { diff = tt1 + tt2; } else { diff = tt1 - tt2; }
t1[0] = Math.abs(Math.floor(parseInt(diff / 60))).padDigit(); // form hours
t1[1] = Math.abs(diff % 60).padDigit(); // form minutes
var tt1 = ''; if (diff < 0) { tt1 = '-'; }
// check for negative value
return document.getElementById("time1").innerHTML = tt1+t1.join(':');
}
</script>
</font>
</body>
</div>
</html>
Enter in the length of the break in the second input field and that time is subtracted from the total.
To make it look fancier, I want the total time to appear as only text, not as an input field.
This is what I have so far:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
</style>
<div id="example2">
<meta charset="utf-8" />
<title> Personal Timer</title>
<script type="text/javascript">
function setTimes(info) {
var sel = info.split('|');
document.getElementById('time1').innerHTML = sel[0];
document.getElementById('time2').value = sel[1];
}
</script>
</head>
<body bgcolor="#0CD6C7">
<div id="example1">
<hr align="left" size="0.5" color="white" width="82%">
<br>
<font size="60" face="verdana" color="white">
<p id="time1"><font size="80"><b>50:00</b></p>
<font size="3" face="verdana">
<input id="time2" value="ex: 2:36" onfocus="this.value=''" size="5"> Type in the length of your break<br>
<button onclick="document.getElementById('time1').value = timeAddSub('time1', 'time2', false)">Enter</button>
<script type="text/javascript">
// From: http://www.webdeveloper.com/forum/showthread.php?273699-add-2-fields-containing-time-values-in-hh-mm-format&daysprune=30
Number.prototype.padDigit = function() {
return (this < 10) ? '0'+this : ''+this;
}
function timeAddSub(id1, id2, flag) { // flag=true to add values and flag=false to subtract values
var tt1 = document.getElementById(id1).value; if (tt1 == '') { return ''; }
var t1 = tt1.split(':');
var tt2 = document.getElementById(id2).value; if (tt2 == '') { return ''; }
var t2 = tt2.split(':');
tt1 = Number(t1[0])*60+Number(t1[1]);
tt2 = Number(t2[0])*60+Number(t2[1]);
var diff = 0; if (flag) { diff = tt1 + tt2; } else { diff = tt1 - tt2; }
t1[1] = Math.abs(diff % 60).padDigit(); // form minutes
t1[0] = Math.abs(Math.floor(parseInt(diff / 60))).padDigit(); // form hours
var tt1 = ''; if (diff < 0) { tt1 = '-'; }
// check for negative value
return document.getElementById("time1").innerHTML = tt1+t1.join(':');
}
</script>
</font>
</body>
</div>
</html>
I know I need to use innerHTML, but it's just not quite clicking. Any pointers in the right direction would be much appreciated!
Change the below line
var tt1 = document.getElementById(id1).value;
to
var p = document.getElementById(id1);
var tt1 = p.textContent;
This is because, value function is applicable only to input tags. For the other plain text tags like p, headings, etc. textContent should be fetched.
What wrong is since t1 is a p tag, it doesn't have value so tt1.split(':'); will throw an exception. Use innerText instead.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
</style>
<div id="example2">
<meta charset="utf-8" />
<title> Personal Timer</title>
<script type="text/javascript">
function setTimes(info) {
var sel = info.split('|');
document.getElementById('time1').innerHTML = sel[0];
document.getElementById('time2').value = sel[1];
}
</script>
</head>
<body bgcolor="#0CD6C7">
<div id="example1">
<hr align="left" size="0.5" color="white" width="82%">
<br>
<font size="60" face="verdana" color="white">
<p id="time1"><font size="80"><b>50:00</b></p>
<font size="3" face="verdana">
<input id="time2" value="ex: 2:36" onfocus="this.value=''" size="5"> Type in the length of your break<br>
<button onclick="document.getElementById('time1').value = timeAddSub('time1', 'time2', false)">Enter</button>
<script type="text/javascript">
// From: http://www.webdeveloper.com/forum/showthread.php?273699-add-2-fields-containing-time-values-in-hh-mm-format&daysprune=30
Number.prototype.padDigit = function() {
return (this < 10) ? '0'+this : ''+this;
}
function timeAddSub(id1, id2, flag) { // flag=true to add values and flag=false to subtract values
var tt1 = document.getElementById(id1).innerText;
if (tt1 == '') { return ''; }
var t1 = tt1.split(':');
var tt2 = document.getElementById(id2).value; if (tt2 == '') { return ''; }
var t2 = tt2.split(':');
tt1 = Number(t1[0])*60+Number(t1[1]);
tt2 = Number(t2[0])*60+Number(t2[1]);
var diff = 0;
if (flag) { diff = tt1 + tt2; } else { diff = tt1 - tt2; }
t1[1] = Math.abs(diff % 60).padDigit(); // form minutes
t1[0] = Math.abs(Math.floor(parseInt(diff / 60))).padDigit(); // form hours
var tt1 = ''; if (diff < 0) { tt1 = '-'; }
// check for negative value
return document.getElementById("time1").innerHTML = tt1+t1.join(':');
}
</script>
</font>
</body>
</div>
</html>
Needing to validate that user inputs date that is not before 2014 or after the current date. I tried splitting the date entry by "/" and then using parseInt to catch if the [2] spot was less than 2014 but it doesn't seem to work!
<!DOCTYPE HTML>
<html>
<head>
<style>
form {border-style: inset;
border-color: blue;
height: 360px;
width: 775px;
margin: auto;
}
</style>
<script>
//Declares 3 arrays
var fullNames = new Array(100);
var dates = new Array(100);
var opinions = new Array(100);
//Global variable
var numOfRatings = 0;
</script>
<script>
//Validates fields are not empty, date is correct then assigns data to arrays
function validateData()
{
var fullNameStr = document.getElementById("FullName").value;
var dateStr = document.getElementById("Date").value;
var opinionStr = document.getElementById("opinion").value;
if (!fullNameStr||!opinionStr||!dateStr) {
alert("Please complete all fields.");
return;
}
else {
var dateVal = dateStr;
var dateParts = dateVal.split("/");
if (parseInt(dateParts[2]) < "2014") {
alert("Invalid date!");
}
else {
fullNames[numOfRatings] = fullNameStr;
dates[numOfRatings] = dateStr;
opinions[numOfRatings] = opinionStr;
numOfRatings++;
document.getElementById("FullName").value = "";
document.getElementById("Date").value = "";
document.getElementById("opinion").value = "";
}
}
}
</script>
<script>
//Displays data held in arrays
function displayData()
{
var col;
var pos;
document.getElementById("list").value = "FULL NAME DATE RATING\n";
for (pos = 0; pos < numOfRatings; pos++)
{
document.getElementById("list").value += fullNames[pos];
for (col = fullNames[pos].length; col <= 25; col++)
document.getElementById("list").value += " ";
document.getElementById("list").value += dates[pos];
for (col = dates[pos].length; col <= 15; col++)
document.getElementById("list").value += " ";
document.getElementById("list").value += opinions[pos]+ "\n";
}
}
</script>
<script>
//Clears form
function clearData()
{
var pos;
for (pos = 0; pos < numOfRatings; pos++)
{
fullNames[pos] = "";
dates[pos] = "";
opinions[pos] = "";
}
numOfRatings = 0;
}
</script>
</head>
<h1 style ="text-align:center; border-bottom:1px solid #999999">Internet Technologies Membership</h1>
<form name ="ratingForm">
<table cellpadding="10">
<td>
<tr>
<td>Full Name:</td>
<td><input type="text" id="FullName" name="FullName"></td>
<td>Date:</td>
<td><input type="date" id="Date" name="Date"></td>
<td>Opinion:</td>
<td>
<select name="opinion" id="opinion">
<option value="★★★★★">Excellent</option>
<option value="★★★★">Very Good</option>
<option value="★★★">Good</option>
<option value="★★">Fair</option>
<option value="★">Poor</option>
<option value="0">Very Bad</option>
</select>
</td>
</tr>
</table>
<br>
<center>
<textarea name="list" id="list" rows="10" cols="100">
</textarea>
<br>
<br>
<input type="button" value="RATE" onClick="validateData();">
<input type="button" value="DISPLAY" onClick="displayData();">
<input type="reset" value="CLEAR" onClick="clearData();">
<br>
</center>
</form>
</html>
The date will be retrieved in YYYY-MM-DD format irrespective of what is displayed in the input box.
Try to split it by hyphen (-).
Also while comparing use 2014 as a number instead of string
var dateParts = dateVal.split("-");
if (parseInt(dateParts[0]) < 2014)
if (parseInt(dateParts[2]) < "2014") {
The above part of code is checking the dateParts[2] (an Int) with a string.
You have to make the "2014" part as an Integer too.
So the above line should be
if (parseInt(dateParts[2]) < 2014) {
Also I would suggest using MomentJS for any DateTime related functionality.
I'm trying to write the code to get the "date" excluding weekends and bank holidays( which means when I enter the date and number of days, it should exclude weekends and bank holidays, like when I give 03-24-2017 and 3 days, it should give 03-31-2017 assuming 29th is a holiday). I got the code for whole thing, but it is taking todays date, but I wish to enter the date manually, I tried with document.getElementById("today").value; but its not giving any output.Thanks in advance.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title> Add Days and Holidays </title>
</head>
<body>
<pre id="fourWeeks"></pre>
Add <input id="nDaysToAdd" value="0"> days<p>
<button onclick="calcBusinessDay()"> Calculate
</button>
<div id="debug"</div>
<script type="text/javascript">
var today = new Date();
var holidays = [
[2017,2,10],
before holiday
[2017,7,4],
];
Date.prototype.addDays = function (days) { return new
Date(this.getTime() + days*24*60*60*1000); }
Date.prototype.addBusAndHoliDays = function (days) {
var cDate = this;
var holiday = new Date();
var c='', h='';
for (var i=1; i<=days ; i++){
cDate.setDate(cDate.getDate() + 1);
if (cDate.getDay() == 6 || cDate.getDay() == 0) {
days++; }
else {
for (j=0; j<holidays.length; j++) {
holiday = new
Date(holidays[j][0],(holidays[j][1]-1),holidays[j][2]);
c = cDate.toDateString(); h =
holiday.toDateString();
if (c == h) { days++; }
}
}
} return cDate;
}
Date.prototype.DayList = function (daysToShow) {
var td = this;
if (daysToShow == undefined) { daysToShow = 31; }
var str = '';
for (var i=0; i<daysToShow; i++) {
newday = new
Date(td.getFullYear(),td.getMonth(),(td.getDate()+i));
str += newday.toDateString()+'\t =>\t'+i+' actual days
ahead<br>';
} return str;
}
function calcBusinessDay() {
functions
var today = new Date();
var N =
parseInt(document.getElementById('nDaysToAdd').valu
e) || 0;
var wd = today.addDays(N);
document.getElementById('debug').innerHTML
= '<p>'+N+' week days from today
('+today.toDateString() +') will be on:
'+wd.toDateString();
var bd = today.addBusAndHoliDays(N);
document.getElementById('debug').innerHTML +=
'<p>'+N+' business days will be on: '+bd.toDateString();
str += '<p>'+newDay.DayList(14);
document.getElementById('debug').innerHTML +=
'<p>'+str;
}
</script>
</body>
</html>
With document.getElementById("today").value you get the value of an INPUT html element, and you don't have any input with todays value.
Here's an snippet getting todays date (Warning: the date is formatted d/m/y)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://cdn.rawgit.com/JDMcKinstry/JavaScriptDateFormat/master/Date.format.min.js"></script>
</head>
<body>
Today: <input id="today" type="text">
<br>
<button onclick="calculate()" >Calculate something</button>
<div id="results" style="margin-top: 20px; border: red;"></div>
<script>
document.getElementById("today").value = new Date().format('d/m/Y');
function calculate() {
var splitted = document.getElementById("today").value.split("/");
var today = new Date(splitted[2], splitted[1] - 1, splitted[0]);
document.getElementById("results").innerHTML = "Today is " + today;
}
</script>
</body>
</html>
I am have displayed the Timer and Countdown Timer from 59 seconds to 0 seconds in decrease order using AngularJS. I have 2 problems,can anyone help to solve this 2 problems
Problem 1:
But there is a problem in displaying the countdown time i.e. it is displaying the alert message before 0:1 seconds .But it should display the alert message after the count completes form 59 to 0 seconds.
code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UFT-8">
<link rel="stylesheet" href="menu.css">
<link rel="stylesheet" href="layout.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script>
var pos = 0, test, test_status, question, choice, choices, chA, chB, chC, correct = 0;
var questions = [
[ "Which of the following a is not a keyword in Java ?", "class", "interface", "extends", "C" ],
[ "Which of the following is an interface ?", "Thread", "Date", "Calender", "A" ],
[ "Which company released Java Version 8 ?", "Sun", "Oracle", "Adobe", "A" ],
[ "What is the length of Java datatype int ?", "32 bit", "16 bit", "None", "C" ],
[ "What is the default value of Java datatype boolean?","true","false","0","A"]
];
function _(x){
return document.getElementById(x);
}
function renderQuestion(){
test = _("test");
if(pos >= questions.length){
var showscore=Math.round(correct/questions.length*100);
var minuteleft = parseInt((totalsecoriginal-totalsec) / 60, 10);
var sec = (totalsecoriginal-totalsec) - (minuteleft * 60);
document.getElementById("online_start").src = "animatedthankyou.gif";
document.getElementById("showtime")
test.innerHTML = "<h3>You got "+correct+" correct of "+questions.length+" questions</h3>";
test.innerHTML += "<h3> Your Grade : "+showscore +"% </h3>";
test.innerHTML += "<h4>Exam Finished in Time :" + minuteleft + " Minutes :" + sec + " Seconds</h4>";
test.innerHTML += "<button onclick='EndExam()'>End the Exam</button>";
_("test_status").innerHTML = "<h3>Test Completed</h3>";
pos = 0;
correct = 0;
clearTimeout(tim);
document.getElementById("starttime").style.display += 'none';
document.getElementById("showtime").style.display += 'none';
document.getElementById("endtime").style.display += 'none';
return false;
}
_("test_status").innerHTML = "<h3>Question "+(pos+1)+" of "+questions.length+"</h3>";
question = questions[pos][0];
chA = questions[pos][1];
chB = questions[pos][2];
chC = questions[pos][3];
test.innerHTML = "<h3>"+question+"</h3>";
test.innerHTML += "<input type='radio' name='choices' value='A'> "+chA+"<br>";
test.innerHTML += "<input type='radio' name='choices' value='B'> "+chB+"<br>";
test.innerHTML += "<input type='radio' name='choices' value='C'> "+chC+"<br><br>";
test.innerHTML += "<button onclick='checkAnswer()'>Next</button><br><br>";
}
function checkAnswer(){
choices = document.getElementsByName("choices");
choice=-1;
for(var i=0; i<choices.length; i++){
if(choices[i].checked){
choice = choices[i].value;
}
}
if(choice == questions[pos][4]){
correct++;
}
pos++;
renderQuestion();
}
window.addEventListener("load", renderQuestion, false);
function EndExam(){
location.href="Loginpage.htm";
}
var tim;
var showscore=Math.round(correct/questions.length*100);
var totalsec = 60;
var totalsecoriginal = totalsec;
var f = new Date();
function starttime() {
showtime();
var showcurtime = moment();
var curtimeformat = showcurtime.format('h:mm:ss a');
var showendtime = showcurtime.add(totalsec, 's');
var endtimeFormat = showendtime.format('h:mm:ss a');
document.getElementById("starttime").innerHTML = "<h4>Starting Time " + curtimeformat + "</h4>";
document.getElementById("endtime").innerHTML = "<h4>Ending Time " + endtimeFormat + "</h4>";
}
// Using Angular JS
var app = angular.module('MyApp',[])
app.controller('MyController',function($scope,$window,$interval,$timeout,$filter){
var date=new Date();
$scope.hhmmss = $filter('date')(new Date(), 'hh:mm:ss a');
$scope.currentTime = new Date();
$scope.currentTime .setSeconds($scope.currentTime .getSeconds() + 60);
//CountDown TImer
var tim;
$scope.totalsec = 60;
var countdowntime= function(){
$scope.totalsec--;
$scope.min = parseInt($scope.totalsec / 60, 10);
$scope.sec = $scope.totalsec - ($scope.min * 60);
if($scope.sec >0){
tim = $timeout(countdowntime, 1000);
}else if($scope.sec== 0){
$timeout.cancel(tim);
$window.alert("Time Up");
}
};
countdowntime();
});
</script>
</head>
<body onload="starttime()" >
<div id="Holder">
<div id="Header"></div>
<div id="NavBar">
<nav>
<ul>
<li> Login</li>
<li>Registration</li>
</ul>
</div>
<div id="Content">
<div id="PageHeading">
<h1><marquee direction="right" behavior="alternate">All the Best</marquee></h1>
</div>
<div id="ContentLeft">
<h2></h2><br>
<img id="online_start">
<br>
<h6>Online Examination System(OES) is a Multiple Choice Questions(MCQ) based
examination system that provides an easy to use environment for both
Test Conducters and Students appearing for Examination.</h6>
</div>
<div id="ContentRight">
<section class="loginform_cf">
<div ng-app="MyApp" ng-controller="MyController" ng-init="StartTimer()">
<table>
<tr>
<td id="test_status" style="text-align:left" ></td>
<td> Exam Starts :<span ng-bind = "hhmmss"> </span> </td>
<td> Exam Ends : {{currentTime | date:'HH:mm:ss a'}} </td>
</tr>
<tr>
<td id="test" colspan="3"></td>
</tr>
</table>
<br>
Your Left Time is :{{min}} Minutes:{{sec}} Seconds<br>
</div>
<br>
</section>
</div>
</div>
<div id="Footer">Developed by - K.P.RAJU</div>
</div>
<script src="moment.js"></script>
</body>
</html>
Problem 2:
At the end of the exam Exam Starts :10:35:39 AM and Exam Ends : 10:36:39 AM timer should disable .The page should display as shown below
Test Completed
You got 0 correct of 5 questions
Your Grade : 0%
Exam Finished in Time :0 Minutes :4 Seconds
To try solve your 1st problem, try putting alert inside timeout, like
$timeout(function() {
$window.alert("Time Up");
},0);
Because JavaScript is single thread, AngularJS must be run in callback mode, so the alert is called before AngularJS rendering getting called.
2nd, sorry didn't get you
I have changed your code to angular and used interval to run the time and ng-show and ng-hide directives.
SCRIPT and HTML
var app = angular.module('MyApp', [])
app.controller('MyController', function($scope, $compile, $window, $interval, $timeout, $filter) {
$scope.pos = 0, $scope.correct = 0, $scope.ques = true;
$scope.questions = [
["Which of the following a is not a keyword in Java ?", "class", "interface", "extends", "C"],
["Which of the following is an interface ?", "Thread", "Date", "Calender", "A"],
["Which company released Java Version 8 ?", "Sun", "Oracle", "Adobe", "A"],
["What is the length of Java datatype int ?", "32 bit", "16 bit", "None", "C"],
["What is the default value of Java datatype boolean?", "true", "false", "0", "A"]
];
$scope.totalsecoriginal = $scope.totalsec = 60;
$scope.totalsec--;
$scope.min = parseInt($scope.totalsec / 60, 10);
$scope.sec = $scope.totalsec - ($scope.min * 60);
$scope.date = new Date();
$scope.hhmmss = $filter('date')(new Date(), 'hh:mm:ss a');
$scope.currentTime = new Date();
$scope.currentTime.setSeconds($scope.currentTime.getSeconds() + 60);
function _(x) {
console.log(angular.element(document.getElementById(x)));
return angular.element(document.getElementById(x))[0];
}
$scope.interval = $interval(function() {
if ($scope.sec === 0) {
$scope.min--;
$scope.sec = 60;
}
$scope.sec--;
}, 1000);
$scope.$watch('sec', function() {
if ($scope.min === 0 && $scope.sec === 0) {
$interval.cancel($scope.interval);
window.alert('Time Up!!!');
$scope.pos = $scope.questions.length;
$scope.temp = true;
$scope.renderQuestion();
}
})
$scope.renderQuestion = function() {
if ($scope.pos >= $scope.questions.length) {
$scope.ques = false;
if (!$scope.temp) { $scope.temp = false;
$interval.cancel($scope.interval);
}
$scope.showscore = Math.round($scope.correct / $scope.questions.length * 100);
$scope.minuteleft = parseInt(($scope.totalsecoriginal - $scope.totalsec) / 60, 10);
$scope.pos = 0;
return false;
}
$scope.question = $scope.questions[$scope.pos][0];
$scope.chA = $scope.questions[$scope.pos][1];
$scope.chB = $scope.questions[$scope.pos][2];
$scope.chC = $scope.questions[$scope.pos][3];
}
$scope.checkAnswer = function() {
$scope.choices = angular.element(document.getElementsByName('choices'));
$scope.choice = -1;
for (var i = 0; i < $scope.choices.length; i++) {
if ($scope.choices[i].checked) {
$scope.choice = $scope.choices[i].value;
$scope.choices[i].checked = false;
}
}
if ($scope.choice == $scope.questions[$scope.pos][4]) {
$scope.correct++;
}
$scope.pos++;
$scope.renderQuestion();
}
$scope.renderQuestion();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<div id="Holder">
<div id="Header"></div>
<div id="NavBar">
<ul>
<li> Login</li>
<li>Registration</li>
</ul>
</div>
<div id="Content">
<div id="PageHeading">
<h1><marquee direction="right" behavior="alternate">All the Best</marquee></h1>
</div>
<div id="ContentLeft">
<h2></h2>
<br>
<img id="online_start">
<br>
<h6>Online Examination System(OES) is a Multiple Choice Questions(MCQ) based
examination system that provides an easy to use environment for both
Test Conducters and Students appearing for Examination.</h6>
</div>
<div id="ContentRight">
<section class="loginform_cf">
<div ng-app="MyApp" ng-controller="MyController" ng-init="StartTimer()">
<table>
<tr>
<td id="test_status" style="text-align:left">
<h3 ng-show='ques'>Question {{pos+1}} of {{questions.length}}</h3>
<h3 ng-hide='ques'>Test Completed </h3>
</td>
<td ng-show='ques'> Exam Starts :<span ng-bind="hhmmss"> </span> </td>
<td ng-show='ques'> Exam Ends : {{currentTime | date:'hh:mm:ss a'}} </td>
</tr>
<tr>
<td id="test" colspan="3">
<div ng-show="ques">
<h3>{{question}}</h3>
<input type='radio' name='choices' value='A'>{{chA}}
<br>
<input type='radio' name='choices' value='B'>{{chB}}
<br>
<input type='radio' name='choices' value='C'>{{chC}}
<br>
<br>
<button ng-click='checkAnswer()'>Next</button>
</div>
<div ng-hide='ques'>
<h3>You got {{correct}} correct of {{questions.length}} questions</h3>
<h3> Your Grade : {{showscore}}% </h3>
<h4>Exam Finished in Time :{{minuteleft}} Minutes {{sec}} Seconds</h4>
<button ng-click='EndExam()'>End the Exam</button>
</div>
<br>
<br>
</td>
</tr>
</table>
<br> Your Left Time is :{{min}} Minutes {{sec}} Seconds
<br>
</div>
<br>
</section>
</div>
</div>
<div id="Footer">Developed by - K.P.RAJU</div>
</div>
</body>