How do i stop a button from time counter? - javascript

I have a button when clicked its starts the count right so now i want it to stop the count when clicked again. so i that ican be able to click any other button and that button must do exactly as the first one
any will be much appreciated.
This is how the button created
function createButtons(tbID, tbClass, tbType, tbValue, onClick) {
return '\n<input '
+ (tbID ? ' id=\'' + tbID + '\'' : '')
+ (tbClass ? ' class=\'' + tbClass + '\'' : '')
+ (tbType ? ' type=\'' + tbType + '\'' : '')
+ (tbValue ? ' value=\'' + tbValue + '\'' : '')
+ (onClick ? ' onclick=\'toggle(this);' + onClick + '\'' : '')
+ '>';
}
function (i, item) {
newContent += createButtons("tb" + item.CommonCable, null, "submit", item.CommonCable, toggle);
});
The following code is counting the time when button clicked. and display it in an HTML page.
function toggle(ths) {
$(ths).toggleClass("btnColor");
$("#tb").toggleClass("btnColorR");
var clicked = $(ths).val();
$("#setCount").html(" DOWNTIME TYPE : " + clicked + " MINUTES : " + minutes + " SECONDS : " + count );
count = count + 1;
if (count % 60 == 0) {
minutes += 1;
count = 0;
}
timer = setTimeout("toggle()", 1000);
}

All you need to do is add an onClick handler to the stop button, with the following line inside:
timer = null;

Related

Make a Change Log table which logs the changes in drop down menu

I want to make a Change log table which show if there's been a change in the drop down menu.
For example i am working with a worksheet and i have one select menu Results which has options like Positive, Negative, Unknown. I want if anyone changes from Positive to negative or anything else it should log in the change log table with a time stamp.
Currently i have a version which works with the input fields but it is not working when i am making changes in the select field (drop down menu).
This is the code i am using for input fields and this is working fine.
$(document).on('focusin', 'input', function()
{
console.log("Saving value " + $(this).val());
$(this).data('val', $(this).val());
}
).on('change','input', function(){
var prev = $(this).data('val');
var current = $(this).val();
var date1 = Date();
if (prev !== current) {
$(this).css("color", $currentDayColor);
$specimenInfo = "";
if((prev != current) && (prev!= null) && (prev != " ")){
document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML + $specimenInfo + 'The Prev Value is :' + prev +' Which was changed on :'+ date1+'<br>';
document.getElementById("demo2").innerHTML = document.getElementById("demo2").innerHTML + $specimenInfo + ' The Current Value is :' + current +' Which was changed on :'+ date1 + '<br>';
console.log("Prev value " + prev);
console.log("New value " + current);
}
};
});
If your code with input fields is working fine then you just need to replace the 'input' with 'select' in your selector. Like this:
$(document).on('focusin', 'select', function()
{
console.log("Saving value " + $(this).val());
$(this).data('val', $(this).val());
}
).on('change','select', function(){
var prev = $(this).data('val');
var current = $(this).val();
var date1 = Date();
if (prev !== current) {
$(this).css("color", $currentDayColor);
$specimenInfo = "";
if((prev != current) && (prev!= null) && (prev != " ")){
document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML + $specimenInfo + 'The Prev Value is :' + prev +' Which was changed on :'+ date1+'<br>';
document.getElementById("demo2").innerHTML = document.getElementById("demo2").innerHTML + $specimenInfo + ' The Current Value is :' + current +' Which was changed on :'+ date1 + '<br>';
console.log("Prev value " + prev);
console.log("New value " + current);
}
};
});

JavaScript - Remove rows dynamically after 2mins

I am calling a webapi using get method which will give json data and I am display as a table from that data. the code which I have given below is working fine. I got around 25 rows(dynamically" of data when I fit the service. this webpage will be refreshed using signalR. when any changes in DB immediately it should reflect in the webpage.
My question is if "" + item.TakeupType + "" value is "Completed" or "cancelled" this row background should change to gray color and after 2mins row should be remove from the webpage.
Note:
1) Only 22 rows should display on webpage in orderby asc Datetime.
2) Completed/cancelled items from DB should will display on the webpage for 2 mins and drop off.
My code :
Hide Expand Copy Code
//Webapi call - To load info status.
function LoadinfoStatus() {
$.ajaxSetup({
beforeSend: function (xhr) {
xhr.setRequestHeader('x-api-key', '9024024A-024-485C024-6BC2024DA');
}
});
$.ajax({
type: "GET",
url: "https://mywebsites.net/version1/info/494",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// alert(JSON.stringify(data));
$("#DIV").html('');
var DIV = '';
//Function to get DateFormat
function getFormattedDate(date) {
// debugger;
var inputdate = new Date(date);
var currentdate = new Date();
var strTime = getFormattedTime(inputdate);
var rngStrTime = getFormattedTime(add_minutes(inputdate, 5));
if (inputdate > currentdate) {
return inputdate.getDate() + '/' + (inputdate.getMonth() == 0 ? 12 : inputdate.getMonth()) + " " + strTime + " - " + rngStrTime;
}
else {
return strTime + " - " + rngStrTime;
//return day + "/" + month + " - " + strTime;
}
}
var add_minutes = function (dt, minutes) {
return new Date(dt.getTime() + minutes * 60000);
}
function getFormattedTime(inputdate) {
var day = inputdate.getDate();
var month = inputdate.getMonth() + 1;
var hours = inputdate.getHours();
var minutes = inputdate.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
return hours + ':' + minutes + ampm;
}
$.each(data, function (i, item) {
var rows = "<tr ' " + (item.Count > 100 ? "data-id='" + item.orderId + "'" : "") + (item.TakeupType == "Cancelled" ? "style='background-color: gray; color: white'" : "") + " align= 'center' > " +
"" + "" + "" + "" +
"" + item.user.firstName + " " + item.user.lastName.charAt(0) + "." + "" +
"" + item.TakeupType + "" +
"" + (item.Count == undefined ? "$" + " " + 0 : "$" + " " + item.Count) + "" +
"" + getFormattedDate(item.TakeupTimeUtc) + "" +
"= 100 ? "style='background-color: darkorange; color: white'>***" : ">") + "" +
"";
var $tbody = $('tblOrders tbody');
$('#tblOrders').append(rows);
}); //End of foreach Loop
registerEvents();
// console.log(data);
}, //End of AJAX Success function
failure: function (data) {
alert(data.responseText);
}, //End of AJAX failure function
error: function (data) {
alert(data.responseText);
} //End of AJAX error function
});
}

Render a RealTime Clock after append in Jquery

I have tried many ways to make a live clock (with seconds) appear in a rendered table but it's not working propperly. The clock stays static, not showing second by second. I'm doing the following :
function myTable(){
var table = $('<table></table>');
table.append($('<tr>')
.append($('<td>')
.addClass('col2 data')
.attr('rowspan', '2')
.append($('<span>')
.attr('id', 'date_time')
)
)
)
$("#myDiv").html(table)
}
liveClock();
var liveClock = function () {
date = new Date;
//some logic here to generate the data I need the result above ( no problems here )
result = '' + d + '/' + month + '/' + year + ' ' + h + ':' + m + ':' + s;
var setDateTime = function() {
$("#date_time").html(result);
return false;
};
var everySec = setInterval(setDateTime, 1000);
}
Your problem is that you're never updating result, so each time your code fires SetDateTime, it renders the same date in the table. Move these lines:
date = new Date;
//some logic here to generate the data I need the result above ( no problems here )
result = '' + d + '/' + month + '/' + year + ' ' + h + ':' + m + ':' + s;
Into your setDateTime function.

Change countdown when refresh the page?

I have my own webshop and on the home page i have a lot of products with countdown.
So whats the problem?
The problem is, when i have many javascripts on home page then the broser will freezing, getting slow.
How i know this is an javascript problem ? I tried to disable javascript on the browser and my website works normal.
/*!
*
* Brian2000: BK_Countdown v1.1
* AKA: Brian's jQuery Robust Date/Time Countdown
* http://brian2000.com
*
* Copyright 2012-2013, Brian Kennedy
* Licensed under the GPL Version 3 license
* http://www.gnu.org/licenses/gpl-3.0.en.html
*
* Date: Wed Jan 9 2013 2:54PM EST
*
* You can't remove this part, and if you make changes or improve things, please keep me informed.
* Thank you, enjoy, and support Open Source!
*/
/*
This portion explains how to use the counter, I recomend not deleting it either ;-)
VARS [required]
------------------------------------------------
container: ID of Element for counter
targetDate: MM/DD/YYYY
targetTime: HH:MM:SS (0-23 Hour) [seconds are optional]
OPTIONS:
------------------------------------------------
order: format/output order
order: 1 = Label + Spacer + Value
order: 2 = Value + Spacer + Label (reverse from order 1)
spacer: text/string seperator between label and value
element: html element for label and value containers (default is span)
end: Message to display when date has passed
dayOf: Message to display on day of counter expiration
*/
function BK_CountDown(container, targetDate, targetTime, opts) {
/////////////////////////////////////////////////////
//vars
this.opts = opts;
this.complete = false; //for exiting interval
this.container = container; //target
DArray = targetDate.split('/');
this.targetDate = DArray[0] + '/' + DArray[1] + '/' + DArray[2];
TArray = targetTime.split(':');
this.targetHour = TArray[0]; //hr
this.targetMin = TArray[1]; //min
if (typeof TArray[2] == 'undefined') { //sec
this.targetSec = 0;
}else{
this.targetSec = TArray[2];
}
/////////////////////////////////////////////////////
// options
var defaults = {
'order' : "1",
'spacer' : ':',
'element' : 'span',
'end' : "Deal is ended!",
'dayOf' : "Deal is ended!"
}
if(typeof this.opts != "undefined") { //if options were assigned...
for(var i in defaults) { //assign defaults for unchanged opts
if(typeof this.opts[i] == "undefined") {
this.opts[i] = defaults[i];
}
}
}else{ //no options were assigned
this.opts = defaults;
}
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//////// assembly
/////////////////////////////////////////////////////
s = this.opts['spacer'];
this.c = container.substring(1);
e = this.opts['element'];
if(this.opts['order'] == 2){
//reverse assembly
$(container).append('<' + e + ' id="' + this.c + '_count_days" class="count_days"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_days" class="txt_days">' + s + ' Days</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_hours" class="count_hours"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_hours" class="txt_hours">' + s + ' :</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_min" class="count_min"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_min" class="txt_min">' + s + ' :</' + e + '>');
}
else{
//default assembly
$(container).append('<' + e + ' id="' + this.c + '_txt_days" class="txt_days">Days ' + s + '</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_days" class="count_days"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_hours" class="txt_hours">Hours ' + s + '</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_hours" class="count_hours"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_min" class="txt_min">Minutes ' + s + '</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_min" class="count_min"></' + e + '>');
}
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//////// Count Update function
this.count_update = function count_update(){
date = new Date(); //NOW
targetDate = new Date(this.targetDate);
targetDate.setHours(this.targetHour);
targetDate.setMinutes(this.targetMin);
targetDate.setSeconds(this.targetSec);
var UDate = Math.round(date.getTime()/1000);
var UTargetDate = Math.round(targetDate.getTime()/1000);
differance = UTargetDate - UDate;
days=Math.floor(differance/(60*60*24)*1);
hours=Math.floor((differance%(60*60*24))/(60*60)*1);
minutes=Math.floor(((differance%(60*60*24))%(60*60))/(60)*1);
seconds=Math.floor((((differance%(60*60*24))%(60*60))%(60))*1);
//if range is 0 don't display range
//days
if(days <= 0){$(this.container + '_count_days').remove();$(this.container + '_txt_days').remove();}
else{$(this.container + '_count_days').text(days);}
//hours
if(days <= 0 && hours <= 0){$(this.container + '_count_hours').remove();$(this.container + '_txt_hours').remove();}
else{$(this.container + '_count_hours').text(hours);}
//min
if(days <= 0 && hours <= 0 && minutes <= 0){$(this.container + '_count_min').remove();$(this.container + '_txt_min').remove();}
else{$(this.container + '_count_min').text(+minutes);}
//seconds
$(this.container + '_count_sec').text(seconds);
//Singular text for 'reverse' assembly
if(this.opts['order'] == 2){
if(days <= 1){$(this.container + '_txt_days').text(this.opts['spacer'] + ' dag en ');}
else{$(this.container + '_txt_days').text(this.opts['spacer'] + ' dagen en ')}
if(hours == 1){$(this.container + '_txt_hours').text(this.opts['spacer'] + ' uur en ');}
else{$(this.container + '_txt_hours').text(this.opts['spacer'] + ' uur en ');}
if(minutes == 1){$(this.container + '_txt_min').text(this.opts['spacer'] + ' min');}
else{$(this.container + '_txt_min').text(this.opts['spacer'] + ' min');}
if(seconds == 1){$(this.container + '_txt_sec').text(this.opts['spacer'] + '');}
else{$(this.container + '_txt_sec').text(this.opts['spacer'] + '');}
}
//end of countdown
if(days <= 0 && hours <= 0 && minutes <= 0 && seconds <= 0){
//timer is over, final output
//if date is today!
if(new Date().toDateString() == targetDate.toDateString()){
$(this.container).addClass('count_now');
$(this.container).text(this.opts['dayOf']);
}else{//if date is after today
$(this.container).addClass('count_end');
$(this.container).text(this.opts['end']);
}
this.complete = true;
}
};
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//run immediately
this.count_update();
//now loop this every second
var selfobject = this; //scope gets lost within setInterval (see: http://www.vonloesch.de/node/32)
var theCounter = setInterval(function(){
selfobject.count_update();
if(selfobject.complete == true){
clearInterval(theCounter);}
}, 1000);
}
HTML:
$(document).ready(function() {
var aanbiedingcountdown = new BK_CountDown('#deal1', '05/25/2014', '23:57', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal2', '05/26/2014', '23:57', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal3', '05/28/2014', '23:57', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal4', '05/28/2014', '15:10', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal5', '05/26/2014', '23:57', {order: 2, spacer: ''});
});
You see, for every countdown that i want i need to create an ID.
But what i want is that when the page load, the countdown dont need to run, it makes my website slower. So, only when the someone refresh the page then he get the right date & time.
Example: Time is now 16:00u, the countdown are set at 17h, so, when someone is still on my website (10min) without refreshing the page then the countdown is still 16h only if he refresh the page then countdown is 16:10h...
I've seen this on other websites and they have more than 100 products with countdowns on the same page and still works perfect because timer is not running only if people refresh the page the the timer will set to right date & time.
Demo: http://jsfiddle.net/uJk73/ (i removed seconds, i though site will go faster without this, but no succes)
Hope someone can help my with this.
Updated jsfiddle
So let's say you had 9 deals
<div id="countdowntimer">
<div id="deal1"></div>
<div id="deal2"></div>
<div id="deal3"></div>
<div id="deal4"></div>
<div id="deal5"></div>
<div id="deal6"></div>
<div id="deal7"></div>
<div id="deal8"></div>
<div id="deal9"></div>
</div>
Get rid of this loop in BK_CountDown()
//now loop this every second
/*var selfobject = this; //scope gets lost within setInterval (see: http://www.vonloesch.de/node/32)
var theCounter = setInterval(function(){
selfobject.count_update();
if(selfobject.complete == true){
clearInterval(theCounter);}
}, 1000);
*/
Then
$(document).ready(function() {
var deals = []; // create an array
deals.push( new BK_CountDown('#deal1', '05/24/2014', '23:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal2', '05/24/2014', '22:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal3', '05/24/2014', '12:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal4', '05/24/2014', '13:49', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal5', '05/24/2014', '14:49', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal6', '05/24/2014', '15:57', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal7', '05/24/2014', '15:58', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal8', '05/24/2014', '15:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal9', '05/24/2014', '16:00', {order: 2, spacer: ''}) );
var dealcounter = setInterval(function(){ // create one setTimeout
if (deals.length){
for (i in deals){
var selfobject = deals[i];
selfobject.count_update();
if(selfobject.complete == true) delete deals[i]; // remove from array
}
}else{
clearTimeout(dealcounter); // no more to count down, stop this loop
}
}, 5000); // 5 seconds
});

Passing parameters to a form, via JavaScript

I have a form which passes a number of parameters. So far, the stock parameters are being passed:
var params = "title=" + document.getElementById("title").value +
"&url=" + document.getElementById("url").value +
"&snippet=" + document.getElementById("snippet").value +
"&tags=" + document.getElementById("tags").value +
"&status_bookmark=" + document.getElementById("status_bookmark").value +
"&comment=" + document.getElementById("comment").value +
"&status_comment=" + document.getElementById("status_comment").value;
I'm attempting to append additional form elements to this parameter string, which are:
var i, lng = document.getElementById('addbookmark').length;
// If the length property is undefined, then there is only one checkbox.
if (typeof lng === "undefined") {
params + "&topic-link-item-1=" + document.getElementById("topic-link-item-1").value;
params + "&topic-link-comment-box-1=" + document.getElementById("topic-link-comment-box-1").value;
}
else {
for (i = 0; i < lng; i++) {
params + "&topic-link-item-" + i + "=" + document.getElementById("topic-link-item-" + i).value;
params + "&topic-link-comment-box-" + i + "=" + document.getElementById("topic-link-comment-box-" + i).value;
}
}
Here, I've used code taken from another StackOverflow article, and as you can see, I'm trying to build up a series of paired parameters that match the ad hoc form elements I'm generating elsewhere via jQuery, which works.
However, these values appear not be getting passed via the form, while the other form elements are being passed.
Any suggestions?
Update
I've revised the code, per the suggestions, but it's not working:
var i, formObj = document.form['addbookmark'], formObjLng = document.form['addbookmark'].length;
// If the length property is undefined, then there is only one checkbox.
if ((typeof formObjLng !== "undefined")) {
for (i = 0; i < formObjLng; i++) {
if ((formObj.elements['topic-link-item-' + i].type == "checkbox") && (formObj.elements['topic-link-item-' + i].checked)) {
params = params + "&topic-link-item-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-item-" + i)).value;
params = params + "&topic-link-comment-box-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-comment-box-" + i)).value;
}
}
}
As for the form, it's simply a form with an ID of "addbookmark", and to again state what I said earlier, everything else works with the exception of what Im attempting here.
There are 2 issues with your code. You need to URL encode the values using the encodeURIComponent function. Also you need to assign the result back to the params variable when concatenating:
var params =
"title=" + encodeURIComponent(document.getElementById("title").value) +
"&url=" + encodeURIComponent(document.getElementById("url").value) +
"&snippet=" + encodeURIComponent(document.getElementById("snippet").value) +
"&tags=" + encodeURIComponent(document.getElementById("tags").value) +
"&status_bookmark=" + encodeURIComponent(document.getElementById("status_bookmark").value) +
"&comment=" + encodeURIComponent(document.getElementById("comment").value) +
"&status_comment=" + encodeURIComponent(document.getElementById("status_comment").value);
and also for the other values that you are adding:
var i, lng = document.getElementById('addbookmark').length;
// If the length property is undefined, then there is only one checkbox.
if (typeof lng === "undefined") {
params += "&topic-link-item-1=" + encodeURIComponent(document.getElementById("topic-link-item-1").value);
params += "&topic-link-comment-box-1=" + encodeURIComponent(document.getElementById("topic-link-comment-box-1").value);
}
else {
for (i = 0; i < lng; i++) {
params += "&topic-link-item-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-item-" + i).value);
params += "&topic-link-comment-box-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-comment-box-" + i).value);
}
}
Notice how:
params += "&topic-link-item-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-item-" + i).value);
which is equivalent to:
params = params + "&topic-link-item-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-item-" + i).value);
is not the same as what you were doing initially:
params + "&topic-link-item-" + i + "=" + encodeURIComponent(document.getElementById("topic-link-item-" + i).value);
You were simply concatenating 2 values and never assigning the result back to the params variable.
I'm pretty sure Javascript doesnt' allow text append the way you are doing it.
Should be
params = params +

Categories