I have dynamic data returning in my view as slide, each time i click next button data will save to localStorage and in final slide all data from storage will be send to backend.
The problem with my current code is that I only can reach slide 1 and then next button only stores data but won't go to next slide.
Code
HTML
<div class="answerPanel">
<h4 class="text-center">In order to complete this Quiz successfully, pay attention to timer.</h4>
</div>
Script
$('#projectTable tbody').on( 'click', 'tr', function (e) {
e.preventDefault();
$('.projectName').empty();
$('.answerPanel').html('');
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
$('.answerPanel').append('<h4 class="text-center">In order to complete this Quiz successfully, pay attention to timer.</h4><button id="clicks" class="btn btn-primary">Begin</button>');
$('.projectName').empty();
var projectId = $(this).data('id');
//quizzes
$.ajax({
type:'GET',
url:'{{url('dashboard/getQuizzeswithChoices')}}/'+projectId,
beforeSend: function(data) {
console.log("click - ajax before send", data);
},
success:function(data){
$('.projectName').append('of ', data.project.name);
//return existed data to quizzes
var index = 0;
var countdownTimer = null;
var count = 0;
$("#clicks").click(function(e){
e.preventDefault();
// timer function
function timer(seconds, countdownTimer, callback) {
var days = Math.floor(seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Times Up!";
$("#clicks").attr("disabled", true);
$('.answerPanel').html('<div class="text-center text-danger">OH NO! <br> Times Up!</div>');
} else {
seconds--;
}
//Pass seconds param back to the caller.
callback(seconds);
}
//We pass the countdownTimer param into the timer function as well.
if (countdownTimer != null) {
clearInterval(countdownTimer);
}
if(typeof data.quizzes[index] !== 'undefined'){
seconds = data.quizzes[index].quiz_time;
}
countdownTimer = setInterval(function() {
timer(seconds, countdownTimer, function(_seconds){
seconds = _seconds;
})
}, 1000);
// printing function
if(typeof data.quizzes[index] !== 'undefined'){
var html = '<form id="sendAnswers"> #csrf #method('POST') <div class="row"><div class="col-md-12"><div class="pull-left questionTitle">'+data.quizzes[index].question+'</div><div class="pull-right" id="countdown"></div></div></div>';
if(data.quizzes[index].choices.length > 0){
html+='<div class="col-md-12">';
if(data.quizzes[index].question_type == 'multiple'){
data.quizzes[index].choices.forEach((element, index, array) => {
html+='<div class="checkbox checkbox-primary">';
html+='<input class="checkboxes form-check-input" id="choice" name="checkbox" type="checkbox" value="'+element.choice+'">';
html+='<label class="control-label">'+element.choice+'</label>';
html+='</div>';
});
} else if (data.quizzes[index].question_type == 'single') {
data.quizzes[index].choices.forEach((element, index, array) => {
html+='<div class="radio radio-primary">';
html+='<input class="form-check-input" id="radio" name="radio" type="radio" value="'+element.choice+'">';
html+='<label class="control-label">'+element.choice+'</label>';
html+='</div>';
});
} else {
alert('hi');
data.quizzes[index].choices.forEach((element, index, array) => {
html+='<div class="row">hi';
html+='<input id="input" name="input" type="text">';
html+='<label>'+element.choice+'</label>';
html+='</div>';
});
}
html+='<button id="clicks" type="submit" class="saveSteps btn btn-primary">Next</button></div></form>';
}
$(".answerPanel").html(html);
index++;
}
// if(data.quizzes.length > index) {
// $("#clicks").html("Next");
// }
if(data.quizzes.length === index) {
$("#clicks").html("Send");
$('#clicks').removeClass('btn-primary').addClass('btn-success saveAnswers');
}
//end of printing function
//send form data
$('.saveSteps').unbind().bind('click', function(e){
e.preventDefault();
console.log('saved');
var checkboxes = [];
$("input.checkboxes:checkbox:checked").each(function(){
checkboxes.push($(this).val());
});
// next storage
var radios = [];
$("input.radio:checkbox:checked").each(function(){
radios.push($(this).val());
});
// next storage
var formData = new FormData();
formData.append('checkbox', checkboxes);
formData.append('radio', radios);
$.post({
type: 'POST',
url: '{{route('quizzes.store')}}',
dataType: "json",
processData: false,
contentType: false,
data: formData,
success:function(data){
console.log('data', data);
// $('.answerPanel').html('<h1>Your Score: <span class="text-success">200</span></h1><h4>Thank you for taking this quiz</h4>');
// $("#clicks").hide();
}
});
});
//send form data
});
//return existed data to quizzes
}
// rest of it...
As you can see in this video my data saves successfully but it won't go to next slide (page).
Any idea where the issue might be?
Related
I have made a quiz with JavaScript and want that when the timer is up, it should not let you attempt the quiz anymore and go to the last page which displays the score. The score is displayed by calling displayResult. I have one HTML file and one JS file. When I use setTimeout, even after the time is up, it doesn’t show the score. I think the function doesn’t get called. I have tried using setInterval instead of setTimeout but still it doesn't work. Can someone tell me what I am doing wrong?
Whole code here.
//timer code in quiz.js
const startingMinutes = 1
let time = startingMinutes * 60
const countdownEl = document.getElementById('countdown')
var vri = setInterval(upd, 1000)
function upd() {
const minutes = Math.floor(time / 60)
let seconds = time % 60
seconds = seconds < 10 ? '0' + seconds : seconds
countdownEl.innerHTML = minutes + ":" + seconds
time--
time = time < 0 ? 0 : time
if (time == 0) {
clearInterval(vri);
}
setTimeout(displayResult, 1000);
}
The function gets called you can easily check this by inserting a console.log() inside the function.
When you would like to display the results on the same page then first clear the body and append your new created element on the body.
There is still a bug that your selected elements will always be empty but I just answer your question here "How you display it."
For debugging purposes I set the timer to 6 seconds instead of 60.
(function() {
var allQuestions = [{
question: "The tree sends downroots from its branches to the soil is know as:",
options: ["Oak", "Pine", "Banyan", "Palm"],
answer: 2
}, {
question: "Electric bulb filament is made of",
options: ["Copper", "Aluminum", "lead", "Tungsten"],
answer: 3
}, {
question: "Non Metal that remains liquid at room temprature is",
options: ["Phophorous", "Bromine", "Clorine", "Helium"],
answer: 1
}, {
question: "Which of the following is used in Pencils ?",
options: ["Graphite", "Silicon", "Charcoal", "Phosphorous"],
answer: 0
}, {
question: "Chemical formula of water ?",
options: ["NaA1O2", "H2O", "Al2O3", "CaSiO3"],
answer: 1
}, {
question: "The gas filled in electric bulb is ?",
options: ["Nitrogen", "Hydrogen", "Carbon Dioxide", "Oxygen"],
answer: 0
}, {
question: "Whashing soda is the comman name for",
options: ["Sodium Carbonate", "Calcium Bicarbonate", "Sodium Bicarbonate", "Calcium Carbonate"],
answer: 0
}, {
question: "Which gas is not known as green house gas ?",
options: ["Methane", "Nitrous oxide", "Carbon Dioxide", "Hydrogen"],
answer: 3
}, {
question: "The hardest substance availabe on earth is",
options: ["Gold", "Iron", "Diamond", "Platinum"],
answer: 2
}, {
question: "Used as a lubricant",
options: ["Graphite", "Silica", "Iron Oxide", "Diamond"],
answer: 0
}];
var quesCounter = 0;
var selectOptions = [];
var quizSpace = $('#quiz');
nextQuestion();
$('#next').click(function() {
chooseOption();
if (isNaN(selectOptions[quesCounter])) {
alert('Please select an option !');
} else {
quesCounter += 5;
nextQuestion();
}
});
$('#prev').click(function() {
chooseOption();
quesCounter -= 5;
nextQuestion();
});
function createElement(index) {
var element = $('<div>', {
id: 'question'
});
var header = $('<h2>Question No. ' + (index + 1) + ' :</h2>');
element.append(header);
var question = $('<p>').append(allQuestions[index].question);
element.append(question);
var radio = radioButtons(index);
element.append(radio);
var question1 = $('<p>').append(allQuestions[index + 1].question);
element.append(question1);
var radio1 = radioButtons1(index + 1);
element.append(radio1);
var question2 = $('<p>').append(allQuestions[index + 2].question);
element.append(question2);
var radio2 = radioButtons2(index + 2);
element.append(radio2);
var question3 = $('<p>').append(allQuestions[index + 3].question);
element.append(question3);
var radio3 = radioButtons3(index + 3);
element.append(radio3);
var question4 = $('<p>').append(allQuestions[index + 4].question);
element.append(question4);
var radio4 = radioButtons4(index + 4);
element.append(radio4);
return element;
}
function radioButtons(index) {
var radioItems = $('<ul>');
var item;
var input = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item = $('<li>');
input = '<input type="radio" name="answer" value=' + i + ' />';
input += allQuestions[index].options[i];
item.append(input);
radioItems.append(item);
}
return radioItems;
}
function radioButtons1(index) {
var radioItems1 = $('<ul>');
var item1;
var input1 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item1 = $('<li>');
input1 = '<input type="radio" name="answer1" value=' + i + ' />';
input1 += allQuestions[index].options[i];
item1.append(input1);
radioItems1.append(item1);
}
return radioItems1;
}
function radioButtons2(index) {
var radioItems2 = $('<ul>');
var item2;
var input2 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item2 = $('<li>');
input2 = '<input type="radio" name="answer2" value=' + i + ' />';
input2 += allQuestions[index].options[i];
item2.append(input2);
radioItems2.append(item2);
}
return radioItems2;
}
function radioButtons3(index) {
var radioItems3 = $('<ul>');
var item3;
var input3 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item3 = $('<li>');
input3 = '<input type="radio" name="answer3" value=' + i + ' />';
input3 += allQuestions[index].options[i];
item3.append(input3);
radioItems3.append(item3);
}
return radioItems3;
}
function radioButtons4(index) {
var radioItems4 = $('<ul>');
var item4;
var input4 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item4 = $('<li>');
input4 = '<input type="radio" name="answer4" value=' + i + ' />';
input4 += allQuestions[index].options[i];
item4.append(input4);
radioItems4.append(item4);
}
return radioItems4;
}
function chooseOption() {
selectOptions[quesCounter] = +$('input[name="answer"]:checked').val();
selectOptions[quesCounter + 1] = +$('input[name="answer1"]:checked').val();
selectOptions[quesCounter + 2] = +$('input[name="answer2"]:checked').val();
selectOptions[quesCounter + 3] = +$('input[name="answer3"]:checked').val();
selectOptions[quesCounter + 4] = +$('input[name="answer4"]:checked').val();
}
function nextQuestion() {
quizSpace.fadeOut(function() {
$('#question').remove();
if (quesCounter < allQuestions.length) {
var nextQuestion = createElement(quesCounter);
quizSpace.append(nextQuestion).fadeIn();
if (!(isNaN(selectOptions[quesCounter, quesCounter + 1, quesCounter + 2, quesCounter + 3, quesCounter + 4]))) {
$('input[value=' + selectOptions[quesCounter] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 1] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 2] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 3] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 4] + ']').prop('checked', true);
}
if (quesCounter === 1) {
$('#prev').show();
} else if (quesCounter === 0) {
$('#prev').hide();
$('#next').show();
}
} else {
var scoreRslt = displayResult();
quizSpace.append(scoreRslt).fadeIn();
$('#next').hide();
$('#prev').hide();
}
});
}
const startingMinutes = 0.1;
let time = startingMinutes * 60
const countdownEl = document.getElementById('countdown')
var vri = setInterval(upd, 1000)
function upd() {
const minutes = Math.floor(time / 60)
let seconds = time % 60
seconds = seconds < 10 ? '0' + seconds : seconds
countdownEl.innerHTML = minutes + ":" + seconds
time--
time = time < 0 ? 0 : time
console.log(time);
if (time === 0) {
clearInterval(vri);
setTimeout(displayResult, 1000);
}
}
function displayResult() {
console.log(selectOptions);
var correct = 0;
console.log(selectOptions);
for (var i = 0; i < selectOptions.length; i++) {
if (selectOptions[i] === allQuestions[i].answer) {
correct++;
}
}
document.body.innerHTML = "";
let score = document.createElement("p");
score.id = 'question';
if (correct === 0 && correct <= 5) {
let otherText = document.createTextNode("YOUR IQ SCORES LIES IN THE RANGE OF 70 and 79 WHICH IS CLASSIFIED AS BORDERLINE");
let img = document.createElement("img");
img.src = "img9b.png"
score.append(otherText)
score.append(img);
} else {
let tex = document.createTextNode("The Result is: " + correct);
score.appendChild(tex);
}
document.body.appendChild(score);
}
})();
<html>
<head>
<title>Make Quiz Website</title>
<link rel="stylesheet" href="quiz.css">
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
</head>
<body>
<div id="container">
<h1>Quiz Website Using JavaScript</h1>
<br/>
<div id="quiz"></div>
<p id="countdown">30:00</p>
</h1>
<div class="button" id="next">Next</div>
<div class="button" id="prev">Prev</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
<script src="quiz.js"></script>
</body>
</html>
I have a form for my array of data will print to view with html() and this data each one has child array, I need to get data of those child arrays in my html() as well
Screenshots
my data
how it will look
# Code
HTML
<div class="answerPanel"></div>
<button id="clicks" class="btn btn-primary">Begin</button>
Script
var index = 0;
$("#clicks").click(function(){
// timer function
function timer(seconds, countdownTimer, callback) {
var days = Math.floor(seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Times Up!";
$("#clicks").attr("disabled", true);
$('.answerPanel').html('<div class="text-center text-danger">OH NO! <br> Times Up!</div>');
} else {
seconds--;
}
//Pass seconds param back to the caller.
callback(seconds);
}
//We pass the countdownTimer param into the timer function as well.
var countdownTimer = null,
seconds = data.quizzes[index].quiz_time;
countdownTimer = setInterval(function() {
timer(seconds, countdownTimer, function(_seconds){
seconds = _seconds;
})
}, 1000);
// printing function
if(typeof data.quizzes[index] != 'undefined'){
var row = `<form>
<div class="row">
<div class="col-md-12">
<div class="pull-left questionTitle">
${data.quizzes[index].question}
</div>
<div class="pull-right" id="countdown"></div>
</div>
<div class="col-md-12">
Choice 1
</div>
<div class="col-md-12">
Choice 2
</div>
<div class="col-md-12">
Choice (etc.)
</div>
</div>
</form>`;
$('.answerPanel').html(row);
index++;
}
if(data.quizzes.length > index+1) {
$("#clicks").html("Next");
}
if(data.quizzes.length === index) {
$("#clicks").html("Finish");
}
//end of printing function
});
Any idea?
Please see my code below
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body id="banner">
<ul id="eventCal">
</ul>
<button id="clicks">Click</button>
<script type="text/javascript">
jQuery(document).ready(function($){
var quizzes = [{title:'title1',choices:[{choice:'choice1'},{choice:'choice2'}]},
{title:'title2',choices:[{choice:'new1'},{choice:'new2'}]},
{title:'title3',choices:[{choice:'demo1'},{choice:'demo2'}]}];
var index = 0;
//console.log(quizzes.length)
$("#clicks").click(function(){
if(typeof quizzes[index] != 'undefined'){
var html = '<li><span>'+quizzes[index].title+'</span></li>';
if(quizzes[index].choices.length > 0){
html+='<li class="choises">';
quizzes[index].choices.forEach((element, index, array) => {
//console.log(element.title);
html+='<ul>';
html+='<li><span>'+element.choice+'</span></li>';
html+='</ul>';
});
html+='</li>';
}
$("#eventCal").html(html);
index++;
}
if(quizzes.length === index)
$("#clicks").html("Finish");
})
});
</script>
</body>
Inside of row, you can get the choices by:
let choices = quizzes[index].choices
So I have this code which displays the current timestamp(IST)
<?php echo date("D M d, Y "); ?> </b>
<body onload="digiclock()">
<div id="txt"></div>
<script>
function digiclock()
{
var d=new Date();
var h=d.getHours();
var m=d.getMinutes();
var s=d.getSeconds();
if(s==60)
{
s=0;
m+=1;
}
if(m==60)
{
m=0;
h+=1;
}
if(h==12)
{
h=0;
}
var t=h>=12?'PM':'AM';
document.getElementById('txt').innerHTML=h+":"+m+":"+s+" "+t;
var t=setTimeout(digiclock,500);
}
How to compress this code and how to use it calculate a time limit for terminate a session. For example, a person is playing quiz and the quiz should terminate after 5 minutes and generate the score based on the questions attempted.
Here is example how to use #rckrd's js code snippet with PHP script called by AJAX.
The example is very basic, just to demonstrate implementation logic.
You cann look for live demo here http://demo1.rrsoft.cz/
Download code here http://demo1.rrsoft.cz/test.zip
index.php with HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<button onclick="startQuiz()">Start timer</button>
<div id="messages"></div>
<div id="timerView"></div>
<div id="quiz_body"></div>
<script src="ajax.js"></script>
</body>
</html>
ajax.js with needed functions (I used #rckrd snippet, because is a grat example how to use it with PHP)
// This function has call php script with quiz answer...
var doAnswer = function(number){
var response_value = $('[name="qr'+number+'"]').val();
var response_message = '"Quiz #' + number + ' has successfuly saved';
$('[name="qr'+number+'"]').prop( "disabled", true );
$.ajax({
url: '/answer.php',
type: 'POST',
async: true,
data: {
quiz: number,
value: response_value
},
success:function(response){
if(response === 'OK'){
$('#messages').html(response_message);
}
},
error: function(xhr, type, exception) {
var _msg = "Service through error: ("+xhr.status+") " + exception.toString();
var _err = $('#messages');
_err.text(_msg).show();
}
});
}
// This function just call the php script to render all quiz questions...
var startQuiz = function(){
$.ajax({
url: '/quiz.php',
type: 'GET',
async: true,
data: {
started: true
},
success:function(response){
$('#quiz_body').html(response);
startTimer();
},
error: function(xhr, type, exception) {
var _msg = "Service through error: ("+xhr.status+") " + exception.toString();
var _err = $('#messages');
_err.text(_msg).show();
}
});
}
// Arange elements over time limit
var gameOver = function(){
$('#header').html('Game over');
$('#list').hide();
}
// This function manage time limitation logic and is called when quiz has started...
var startTimer = function (){
var timeLeftInMillis = 1*60*1000;
var startTime = new Date().getTime();
var updateTimeInMillis = 25;
var intervalId = setInterval(function(){
var now = new Date().getTime();
var diffInMills = now - startTime;
startTime = new Date().getTime();
timeLeftInMillis = timeLeftInMillis - diffInMills;
var oneSecondInMillis = 1000;
if(timeLeftInMillis < oneSecondInMillis){
clearInterval(intervalId);
gameOver();
return;
}
var seconds = Math.floor((timeLeftInMillis / 1000) % 60) ;
var minutes = Math.floor((timeLeftInMillis / (1000*60)) % 60);
document.getElementById("timerView").innerHTML = minutes + ' min, ' +seconds+' sec remaining';
},updateTimeInMillis);
};
The quiz.php called by AJAX:
<?php
// very easy list of quizes...
$quiz_template = '
<h1 id="header">Quiz started!</h1>
<ul id="list">
<li>
Quiz 1 text
<input type="text" name="qr1" size="5"/>
<button id="bt1" onclick="doAnswer(1)">Send answer</button>
</li>
<li>
Quiz 2 text
<input type="text" name="qr2" size="5"/>
<button id="bt2" onclick="doAnswer(2)">Send answer</button>
</li>
<li>
Quiz 3 text
<input type="text" name="qr3" size="5"/>
<button id="bt3" onclick="doAnswer(3)">Send answer</button>
</li>
<li>
Quiz 4 text
<input type="text" name="qr4" size="5"/>
<button id="bt4" onclick="doAnswer(4)">Send answer</button>
</li>
<li>
Quiz 5 text
<input type="text" name="qr5" size="5"/>
<button id="bt5" onclick="doAnswer(5)">Send answer</button>
</li>
</ul>
';
// ... and return it
if((bool) $_GET['started'] === true){
die($quiz_template);
}
And Finaly answer.php
<?php
if($_POST){
// grab all needed posted variables... THIS IS JUST FOR DEMO, BECAUSE IS UNSECURED
$quizNumber = $_POST['quiz'];
$quirAnswer = $_POST['value'];
// do quiz PHP logic here, save answer to DB etc...
// when php script runs without errors, just return OK
$error = false;
if($error === false){
die('OK');
}else{
die($someErrorMessage);
}
}
var gameOver = function(){
document.getElementById("timerView").innerHTML = 'Game over';
}
var startTimer = function (){
var timeLeftInMillis = 5*60*1000;
var startTime = new Date().getTime();
var updateTimeInMillis = 25;
var intervalId = setInterval(function(){
var now = new Date().getTime();
var diffInMills = now - startTime;
startTime = new Date().getTime();
timeLeftInMillis = timeLeftInMillis - diffInMills;
var oneSecondInMillis = 1000;
if(timeLeftInMillis < oneSecondInMillis){
clearInterval(intervalId);
gameOver();
return;
}
var seconds = Math.floor((timeLeftInMillis / 1000) % 60) ;
var minutes = Math.floor((timeLeftInMillis / (1000*60)) % 60);
document.getElementById("timerView").innerHTML = minutes + ' min, ' +seconds+' sec remaining';
},updateTimeInMillis);
};
<button onclick="startTimer()">Start timer</button>
<div id="timerView"></div>
If you are open to use third part libraries then check out EasyTimer.js plugin, this will solve the issue.
https://albert-gonzalez.github.io/easytimer.js/
or
countdownjs: http://countdownjs.org/demo.html
This is impossible in php, the best way is use JavaScript/Ajax...
I have code for calculating time difference and it works well. I need to change the method (actually I added one more method in certain condition). The method that I added in a condition when the textbox has value Istirahat, and then I need to change the method to the time difference that I made minus one hour.
I think it will be confusing to see my explanation without the code.
Here's the code:
$(document).ready(function() {
var $time1 = $("#start");
var $time2 = $("#end");
var $diff = $("#jam_total");
function updateHours() {
var dtStart = new Date("7/20/2015 " + $time1.val());
var dtEnd = new Date("7/20/2015 " + $time2.val());
var stats1 = $("#status_check").val();
if(stats1!='ISTIRAHAT') {
var diff = ((dtEnd - dtStart)) / 1000;
} else if(stats1!='TANPA ISTIRAHAT') {
var diff = ((((dtEnd - dtStart)) / 1000) - 1);
}
var totalTime = 0;
if (diff > 60*60*12) {
totalTime = formatDate(60*60*12);
} else {
totalTime = formatDate(diff);
}
$diff.val(totalTime);
}
function formatDate(diff) {
var hours = parseInt(diff / 3600) % 24;
var minutes = parseInt(diff / 60) % 60;
var seconds = diff % 60;
return (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes);
}
$("#option2").on("change", function() {
if($time1.val() && $time2.val()) {
updateHours();
}
});
});
<input type="time" id="start" name="logintime"/>
<input type="time" id="end"name="logouttime" />
<br /><br />
<select name="option2" id="option2" onchange="Choose1(this)" style="float:left">
<option value="-">-</option>
<option value="istirahat">istirahat</option>
<option value="tanpa istirahat">tanpa istirahat</option>
</select>
<input type="text" name="status_check" size="8" readonly="readonly" id="status_check" style="text-transform:uppercase" />
<br /><br />
Total: <input type="text" id="jam_total" type="text" name="jam_total" size="18" readonly="readonly">
<br /><br />
<script>
function Choose1(data) {
document.getElementById("status_check").value = data.value;
}
</script>
Try to check the jQuery function at the code like this:
else if (stats1 != 'TANPA ISTIRAHAT') {
var diff = ((((dtEnd - dtStart)) / 1000) - 1);
}
var diff = (((dtEnd - dtStart)) / 1000) - 1) is what I mean, that code won't work perfectly like I want. What I want is like this:
Please check the code inside if var diff = ((dtEnd - dtStart)) / 1000; I want the result of this code to be minus one hour.
First of all there is one thing wrong, you need to set stats1 to UpperCase, otherwise you can't compare correct. Second thing is you are calculating time over seconds, you should minus 60*60 (3600 to minus 1 hours).
function updateHours(){
var dtStart = new Date("7/20/2015 " + $time1.val());
var dtEnd = new Date("7/20/2015 " + $time2.val());
var stats1 = $("#status_check").val().toUpperCase();
// if you don't add toUpperCase, istirahat won't be equal to ISTIRAHAT so everytime..
// first if block will be executed
if(stats1!='ISTIRAHAT'){
var diff = ((dtEnd - dtStart)) / 1000;
}
else if(stats1!='TANPA ISTIRAHAT'){
var diff = ((((dtEnd - dtStart)) / 1000) - 3600); // and you should minus 3600
}
var totalTime = 0;
if (diff > 60*60*12) {
totalTime = formatDate(60*60*12);
;
} else {
totalTime = formatDate(diff);
}
$diff.val(totalTime);
}
Here is the working fiddle
Hope helps,
I am trying to make a web page which will allow to set multiple alarms using dynamic element creation property of javascript but I'm not able to get the values of these multiple elements and create a alert on that time.
This is my code so far
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var room = 0;
var i = 0;
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = document.getElementById('');
var minute = document.getElementById('');
var date = document.getElementById('');
}
</script>
To create a notification whenever a given time or state is reached, I think you are looking for setInterval (see reference).
This method allows you to take action at a regular interval and it tries to honor that interval the best it can. It opens to a common mistake if your action can take longer than that interval duration so be careful not using a too short interval. In such case, actions can overlap and weird behavior will occur. You do not want that to happen so don't be too greedy when using that.
For an alarm project, I would recommend an interval of one second.
Example (not tested):
JavaScript
var alarmDate = new Date();
alarmDate.setHours(7);
alarmDate.setMinutes(15);
// set day, month, year, etc.
var ONE_SECOND = 1000; // miliseconds
var alarmClock = setInterval(function() {
var currentDate = new Date();
if (currentDate.getHours() == alarmDate.getHours() &&
currentDate.getMinutes() == alarmDate.getMinutes()
/* compare other fields at your convenience */ ) {
alert('Alarm triggered at ' + currentDate);
// better use something better than alert for that?
}, ONE_SECOND);
To add dynamic alarms, you could put them into an array then have your setInterval iterate over it.
In the long run you will probably get sick of alert and feel the need to use something that doesn't break the flow of your application. There are a lot of possibilities, one being the use of lightboxes that could stack over each other. That way you would be able to miss an alarm and still be notified by the next one.
Hope this helps and good luck!
You forgot the ID attribute on the date input and you were collecting the input elements in AddAlarm instead of their values.
EDIT: To check the alarms you have to store them and check every minute, if the current date matches one of the alarms. I added a short implementation there.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var alarms = {};
var room = 0;
var i = 0;
setInterval(function() {
var current = new Date();
for (var nr in alarms) {
var alarm = alarms[nr];
console.log("checking alarm " + nr + " (" + alarm + ")");
if(current.getHours() == alarm.getHours()
&& current.getMinutes() == alarm.getMinutes()) { // also check for day, month and year
alert("ALERT\n"+alarm);
} else{
console.log('Alarm ' + nr + '('+alarm+') not matching current date ' + current);
}
}
}, 60000);
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px" id="c'+room+'"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
console.log(hour + ':' + minute + ' on ' + date);
var dateObj = new Date(date);
dateObj.setMinutes(minute);
dateObj.setHours(hour);
console.log(dateObj);
alarms[values] = dateObj;
}
</script>
So far I'm able to generate a alert when the values match the system time but I don't know how to delete the array value when an element is deleted. I am not able to do it. This is my code so far:
<script type="text/javascript">
var snd = new Audio("clock.mp3"); // buffers automatically when created
// Get
if (localStorage.getItem("test")) {
data = JSON.parse(localStorage.getItem("test"));
} else {
// No data, start with an empty array
data = [];
}
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//since page reloads then we will just check it first for the data
function check() {
//current system values
console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
localStorage["test"] = JSON.stringify(data);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m) )
{
check();
}
}
console.log(data);
var room = 1;
//var data = [];
var i = 0;
function GetDynamicTextBox(){
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var d = date.getDay();
return '<div>Alarm ' + room +':</div><input type="number" style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" value ='+h+' placeholder="hour" id="a'+room+'" /> <input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" value ='+m+' /> <select id="c'+room+'" style="margin:auto; width:150px; padding:10px; color: black" required> <option value="1">Monday</option> <option value="2">Tuesday</option> <option value="3">Wednesday</option> <option value="4">Thursday</option> <option value="5">Friday</option> <option value="6">Saturday</option> <option value="0">Sunday</option> </select> <input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
room++;
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
//get the current time and date
var today = new Date();
//current system values
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//first check that whether a same date present in the array or not then push it
var found = -1;
for(var i = 0; i < data.length; i++) {
if (data[i].hours == hour && data[i].minutes == minute && data[i].dates == date ) {
found = 0;
break;
}
}
//if value does not present then push it into the array
if(found == -1)
{
data.push({hours: hour, minutes: minute, dates: date});
//storing it into localstorage
localStorage.setItem("test", JSON.stringify(data));
}
else
{
alert("Same value Exists");
}
//console.log(data);
function check() {
//current system values
//console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m))
{
check();
}
}
}
</script>