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>
Related
Am trying to create a quiz but after the start page am un sure how to make the answer choices display. I have created the buttons for the choices in html and started them off as hidden, and have allocated for them in javascript. I have the questions and answers in an array but am stuck on displaying the choice buttons under the question. After the initial start page.
<div class="wrapper text-center">
<header>
<h1>Coding Quiz</h1>
</header>
<div class="card">
</div>
<div class="card-body">
<p id="header"> You have 75 seconds to complete this asessment. Every
incorrect answer will cost you time.
<br>
</p>
<button id="start-button" class="btn">Start</button>
<div id="start-game" style="visibility: hidden">
<button id="option0" data-index="0"></button><br>
<button id="option1" data-index="1"></button><br>
<button id="option2" data-index="2"></button><br>
<button id="option3" data-index="3"></button><br>
</div>
</div>
</div>
var timerEl = document.getElementById("timer");
var start = document.getElementById("start-button");
var questionEl = document.getElementById("header");
var option0 = document.getElementById("option0");
var option1 = document.getElementById("option1");
var option2 = document.getElementById("option2");
var option3 = document.getElementById("option3");
var intials = document.getElementById("user-initials");
var buttonEl = document.querySelector("start-game");
var totalTime = 75;
var elapsedTime = 0;
var questionNum = 0;
var questions =["The condition in an if/else statement is enclosed with in _______",
"Arrays in JavaScript can be used to store ______",
"Commonly used data types do not include ______",
"String values must be enclosed within _____ when being assigned to variables"];
var answers =[question1= ["Quotes","Curly brackets","Parentheses","Square brackets"],
question2= ["Numbers and strings","Other arrays","Booleans","All of the above"],
question3= ["Strings","Booleans","Alerts","Numbers"],
question4= ["Commas","Curly brackets","quotes","parentheses"]
];
var correctAnswers = [2,3,2,2];
start.addEventListener("click", function(){
timer();
displayQuestion();
start.style.visibility = "hidden";
buttonEl.style.visibility = "visible";
});
function timer(){
var timerInterval = setInterval(function(){
totalTime--;
timerEl.textContent = totalTime;
if(totalTime === 0){
function stopTimer(){
clearInterval(timerInterval);
endQuiz();
return;
}
}
}, 1000)
}
function newQuiz(){
questionEl.textContent = (questions[0]);
};
function decreaseTimer (){
timerEl.text(totalTime);
while(elapsedTime < 75){
elapesedTime += 1;
}
endQuiz();
totalTime = totalTime - elapsedTime;
timerEl.textContent = totalTime;
}
function displayQuestion(){
for( var i = 0; i < questions.length ; i++){
questionEl.textContent=(questions[i]);
option0.textContent=(answers[i][0]);
option1.textContent=(answers[i][1]);
option2.textContent=(answers[i][2]);
option3.textContent=(answers[i][3]);
}
}
var buttonEl = document.querySelector("start-game");
should be
var buttonEl = document.getElementById("start-game");
var timerEl = document.getElementById("timer");
var start = document.getElementById("start-button");
var questionEl = document.getElementById("header");
var option0 = document.getElementById("option0");
var option1 = document.getElementById("option1");
var option2 = document.getElementById("option2");
var option3 = document.getElementById("option3");
var intials = document.getElementById("user-initials");
var buttonEl = document.getElementById("start-game");
var totalTime = 75;
var elapsedTime = 0;
var questionNum = 0;
var questions =["The condition in an if/else statement is enclosed with in _______",
"Arrays in JavaScript can be used to store ______",
"Commonly used data types do not include ______",
"String values must be enclosed within _____ when being assigned to variables"];
var answers =[question1= ["Quotes","Curly brackets","Parentheses","Square brackets"],
question2= ["Numbers and strings","Other arrays","Booleans","All of the above"],
question3= ["Strings","Booleans","Alerts","Numbers"],
question4= ["Commas","Curly brackets","quotes","parentheses"]
];
var correctAnswers = [2,3,2,2];
start.addEventListener("click", function(){
timer();
displayQuestion();
start.style.visibility = "hidden";
buttonEl.style.visibility = "visible";
});
function timer(){
var timerInterval = setInterval(function(){
totalTime--;
timerEl.textContent = totalTime;
if(totalTime === 0){
function stopTimer(){
clearInterval(timerInterval);
endQuiz();
return;
}
}
}, 1000)
}
function newQuiz(){
questionEl.textContent = (questions[0]);
};
function decreaseTimer (){
timerEl.text(totalTime);
while(elapsedTime < 75){
elapesedTime += 1;
}
endQuiz();
totalTime = totalTime - elapsedTime;
timerEl.textContent = totalTime;
}
function displayQuestion(){
for( var i = 0; i < questions.length ; i++){
questionEl.textContent=(questions[i]);
option0.textContent=(answers[i][0]);
option1.textContent=(answers[i][1]);
option2.textContent=(answers[i][2]);
option3.textContent=(answers[i][3]);
}
}
<div class="wrapper text-center">
<header>
<h1>Coding Quiz</h1>
</header>
<div class="card">
</div>
<div class="card-body">
<p id="header"> You have 75 seconds to complete this asessment. Every
incorrect answer will cost you time.
<br>
</p>
<button id="start-button" class="btn">Start</button>
<div id="start-game" style="visibility: hidden">
<button id="option0" data-index="0"></button><br>
<button id="option1" data-index="1"></button><br>
<button id="option2" data-index="2"></button><br>
<button id="option3" data-index="3"></button><br>
</div>
</div>
</div>
<div id="timer"></div>
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>
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>
i'm a teacher and have just started learning to code for making online quizzes for my students. I'm still very new to programming like JavaScript and php, and I've tried to looked for sources online to help create my quizzes. I have 2 questions:
1). I've set a timer for the quiz but everytime when the time is up, it just keeps counting, what should I put in the
if (parseInt(min) == 0) {
clearTimeout(tim);
location.href = "";
section to redirect my student to the result page or other pages?
(2) My quizzes are mostly fill-in-the-blanks questions and I wonder how to store the point of each question and then show the total score to my students at the end of the quiz? Many thanks!.
Here's my code:
<html>
<head>
<script language ="javascript" >
var tim;
var min = 0;
var sec = 30;
var f = new Date();
function f1() {
f2();
document.getElementById("starttime").innerHTML = "Your started your quiz at " + f.getHours() + ":" + f.getMinutes();
}
function f2() {
if (parseInt(sec) > 0) {
sec = parseInt(sec) - 1;
document.getElementById("showtime").innerHTML = "Your Left Time is :"+min+" Minutes ," + sec+" Seconds";
tim = setTimeout("f2()", 1000);
}
else {
if (parseInt(sec) == 0) {
min = parseInt(min) - 1;
if (parseInt(min) == 0) {
clearTimeout(tim);
location.href = "www.rawlanguages.com";
}
else {
sec = 60;
document.getElementById("showtime").innerHTML = "Your Left Time is :" + min + " Minutes ," + sec + " Seconds";
tim = setTimeout("f2()", 1000);
}
}
}
}
</script>
<title>Quiz</title>
<h1>P.1 Grammar Quiz</h1>
<body>
<div id="ques0" class="ques">
<h2>Question</h2>
<p>She
<input type="text" name="answer0"/> a girl.</p>
</div>
<div id="ques1" class="ques">
<h2>Question</h2>
<p>"is", "am" and "are" are</p>
<ul>
<li>
<input type="radio" name="answer1" value="Present tense" />
<label>Present tense</label>
</li>
<li>
<input type="radio" name="answer1" value="Past tense" />
<label>Past tense</label>
</li>
<li>
<input type="radio" name="answer1" value="Future tense" />
<label>Future tense</label>
</li>
</ul>
</div>
<div id="ques2" class="ques">
<h2>Question</h2>
<p>He
<input type="text" name="answer2"/> a policeman.
</p>
</div>
Check answer!
<script src="JQ.js"></script>
<script src="function.js"></script>
<body onload="f1()" >
<form id="form1" runat="server">
<div>
<table width="100%" align="center">
<tr>
<td colspan="2">
</td>
</tr>
<tr>
<td>
<div id="starttime"></div>
<div id="endtime"></div>
<div id="showtime"></div>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
</div>
</form>
</body>
</head>
</html>
Your code is good enough for a beginner but it requires some improvements.
<script type="text/javascript" >//language ="javascript" is obsolete
//var tim; //no need at all
//var min = 0; //no need at all
//var sec = 30; //there is better way
//var f = new Date(); //no need to be global
function f1(sec) {//define (declare) sec as parameter
f2(); //call the function
var f = new Date();
document.getElementById("starttime").innerHTML = "Your started your quiz at " + f.getHours() + ":" + f.getMinutes();
var showtime = document.getElementById("showtime"); //used many times
//Here we put (closure) f2
function f2() {
//f2 knows sec from parent scope
if (sec <= 0) {//parseInt(sec) no need. sec is int
showtime.innerHTML = 'Time is over';
//ShowAnswers(); //show on the same page or post to .php
return;
}
sec--;// = parseInt(sec) - 1;
showtime.innerHTML = "Your Left Time is :" + Math.floor(sec / 60) +" Minutes ," + (sec % 60) +" Seconds";
setTimeout(f2, 1000);//"f2()" is correct but this way is better
/* no need in remaining code
}
else {
if (parseInt(sec) == 0) {
min = parseInt(min) - 1;
if (parseInt(min) == 0) {
clearTimeout(tim);
location.href = "www.rawlanguages.com";
}
else {
sec = 60;
document.getElementById("showtime").innerHTML = "Your Left Time is :" + min + " Minutes ," + sec + " Seconds";
tim = setTimeout("f2()", 1000);
}
}
}
*/
}//f2
}//f1
</script>
<body onload="f1(90)"><!--Here we send seconds to the function -->
Also note that all your quiz starting from <h1>P.1... must be inside body container.
Hi I unable to connect my javascript file to html. I tried coding everything and now I am unable to see changes in HTML. I am here trying to calculate the tax rate of employees with their overtime worked with tax deduction .
Thanks in advance. Please help.
My code for html is
<!doctype html>
<html>
<head>
<script language="JavaScript" src="employees.js"></script>
<link rel="stylesheet" type="text/css" href="employees.css" />
<title>Pay Form</title>
</head>
<body>
<section id="content">
<h1>
Employee Payroll Entry Form
</h1>
<div id="payForm">
<p>
<label for="fullName">Full Name:</label><input type="text" autofocus id="fullName" />
</p>
<p>
<label for="hoursWorked">Hours Worked:</label><input type="text" id="hoursWorked" />
</p>
<p>
<label for="hourlyRate">Hourly Rate:</label><input type="text" id="hourlyRate" />
</p>
<footer>
<button id="calculateButton" onclick="calculate()">Calculate</button>
</footer>
</div>
<h1>
Employee Payroll Summary Report
</h1>
<table id = "employees">
<tr>
<th>Employee Name</th>
<th>Gross Pay</th>
<th>Tax</th>
<th>Net Pay</th>
</tr>
</table>
</section>
</body>
and my javascript is
var fname = document.getElementById("fullName");
var hours = document.getElementById("hoursWorked");
var rate = document.getElementById("hourlyRate");
var table = document.getElementById("employees");
var gross;
var net;
var tax;
var overtime;
function grosspay() {
if (hours > 0 && hours < 40) {
gross = hours * rate;
} else if (hours < 40) {
overtime = hours - 40;
gross = (40 * rate) + (overtime * (rate * 1.5));
}
}
function taxPay() {
if (gross < 250) {
tax = gross * 0.25;
} else if (gross >= 250 && gross < 500) {
tax = gross * 0.30;
} else if (gross >= 500 && gross < 750) {
tax = gross * 0.40;
} else if (gross > 750) {
tax = gross * 0.50;
}
}
function netPay() {
net = gross - tax;
}
function calculate() {
if (hours > 0)
{
var row = table.insertRow();
var fnamecell = row.insertCell(0);
var grossPaycell = row.insertCell(1);
var taxCell = row.insertCell(2);
var netPayCell = row.insertCell(3);
grosspay();
taxPay();
netPay();
fnamecell.innerHTML = fname;
grossPaycell.innerHTML = grosspay;
taxCell.innerHTML = tax;
netPayCell.innerHTML = net;
}
}
function load() {
var calculateButton = document.getElementById("calculateButtom");
calculateButton.addEventListener("click", calculate);
}
you are get the elements like "hours" but not its value.
Please try the following calculate function and if still got problem please post the debugger output so that others can help you.
function calculate() {
var hoursValue = hours.value;
console.log("Hours are : " + hoursValue );
if (hoursValue > 0)
{
var row = table.insertRow();
var fnamecell = row.insertCell(0);
var grossPaycell = row.insertCell(1);
var taxCell = row.insertCell(2);
var netPayCell = row.insertCell(3);
grosspay();
taxPay();
netPay();
fnamecell.innerHTML = fname;
grossPaycell.innerHTML = grosspay;
taxCell.innerHTML = tax;
netPayCell.innerHTML = net;
}
}
you are get the elements but not its value.
get the values of input fields like:
var hours = document.getElementById("hoursWorked").value;
var rate = document.getElementById("hourlyRate").value;
and also move script tag to the bottom of the page inside body tag.