disable button with PHP and JavaScript when time is gone - javascript

I try to disable Apply button when application deadline is over. I used php and I successfully got time on each button. Now different time is print on different button.
<td><input type='submit' value='Apply' id='button' name='button' date-time='$closedate' /></td>
I used jquery/ javascript to disable button after expired time (after deadline of application), it cannot disable and it always enable.
In the code below code I used for disable button but it not works.
<script>
$(document).ready(function() {
var timer = setInterval(function() {
var current = $("#button").data('time');
// get the current value of the time in seconds
var newtime = current - 1;
if (newtime <= 0) {
// time is less than or equal to 0
// so disable the button and stop the interval function
$("#button").prop('disabled', true);
clearInterval(timer);
} else {
// timer is still above 0 seconds so decrease it
$("#button").data('time', newtime);
}
}, 1000);
});
</script>

based on what you have put down, it seems there are a few simple errors that need to be looked at
1) looks like a simple typo -- date-time should be data-time
2) you are not actually outputting the value of $closedate try changing it to
without knowing what the value of $closedate is, we won't be able to help further than that

Here is a fiddle that replicates an example...https://jsfiddle.net/o2gxgz9r/6656/
Your main issue is that you are mispelling the data-time attribute in your code as date-time. Your html should be as follows...
<input type='submit' value='Apply' id='button' name='button' data-time='$closedate' />
After fixing that, you should be able to reference the data value. Moreover, you are not updating the data value, so every time setInterval is called, the variable $closedate remains the same, and so the if statement if (newtime <= 0) is never reached...
var timer = setInterval(function() {
// get the current value of the time in seconds
var current = $("#button").data('time');
// decrement the time
var newtime = current - 1;
// update $closedate
$("#button").data('time', newtime);
if (newtime <= 0) {
// time is less than or equal to 0
// so disable the button and stop the interval function
$("#button").prop('disabled', true);
clearInterval(timer);
} else {
// timer is still above 0 seconds so decrease it
$("#button").data('time', newtime);
}
}, 1000);
I am not sure what the value of $closedate is but I made an assumption in my fiddle.

A few of issues...
First, in your HTML, you have date-time instead of data-time, so when you go to get the attribute later with: $("#button").data('time'), you won't get anything.
Second, you must remember to convert HTML data (which is always a string) to numbers to do math with them.
Third, you need to verify that $closedate is a string that can be converted into a valid number. You indicated in a comment below that $closedate will be something like: 2017-03-17. But that is not a value that you can subtract from.
Lastly, updating the HTML is costly in terms of performance. You are modifying the data-time attribute upon each iteration of your setInterval(), which is roughly every second. This can and should be avoided. It can be done by keeping the time left in a variable instead of writing it back to the document.
Here's a working version:
$(document).ready(function() {
// Always cache references to elements you will use more than once:
var $btn = $("#button");
// When gettting data from HTML, you get strings. You must convert
// them to numbers to do math with them. Also, we are using 5 seconds
// here instead of $closedate for testing purposes.
var current = parseInt($btn.data('time'), 10);
// Initialize the newtime for comparison
var newtime = current;
var timer = setInterval(function() {
newtime--; // Decrease the time left
// Just testing the variables:
console.log(current, newtime);
if (newtime <= 0) {
// time is less than or equal to 0
// so disable the button and stop the interval function
$btn.prop('disabled', true);
clearInterval(timer);
}
current--; // Decrease the counter
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='submit' value='Apply' id='button' name='button' data-time='5'>

Related

I'm having problem on auto refreshing a content in a web page

I'm creating a webpage that will automatically refresh a content to always get the latest data in the database. This is my code in Javascript.
setInterval(function() {
$("#status").load('refresh.php');
},1000);
In my javascript, I'm automatically refreshing the #status with refresh.php every second.
But when I inspect the element of my webpage and click on the network. It is also requesting(spamming) the refresh.php every second which is I think a bad practice.
Can you help me how to fixed this? Or can you suggest better ajax code to auto refresh a content without requesting the php file too much?
You should probably use a websocket for this, get the latest status as data from the server and then change only that section of the page using javascript
This code will be request refresh.php later at timeouts.min every time when new (requested) value of #status is equal to current. If values are different, next timeout will be timeouts.min again.
var timeouts={
min:1000, // min await timeout = 1s
max:16000 // max await timeout = 16s
};
var currentTo = timeouts.min;
function setAutoRefresh( to ){
setTimeout( function() {
var current = $("#status").text();// or .html()
$("#status").load('refresh.php', function() {
// if we are load a new value
if( current !== $("#status").text()) {
currentTo = timeouts.min;
// if loaded value are same to current
} else {
currentTo += timeouts.min; // or currentTo *= 2; for example
if( currentTo > timeouts.max ){
currentTo = timeouts.max;
}
}
console.log('Next #status refresh after ' + currentTo + 'ms');
// Set a new timeout
setAutoRefresh( currentTo );
});
}, to);
}
// Set the first timeout
setAutoRefresh( timeouts.min );

Show the count up timer result on the page

i want to take out the result of the count up timer and show it on the page by clicking on button.
Here's my solution for your problem,
I just made a simple counter and then each time I trigger the click event it will show the current timer value
The code:
//initialisation
var counterLabel = document.getElementById("counter");
var valueLabel = document.getElementById("value");
var totalSeconds = 0;
counterLabel.innerHTML = totalSeconds;
//the loop each 1s
setInterval(setTime, 1000);
//the function that will increase the conter value and save it into the cookie
function setTime() {
++totalSeconds;
counterLabel.innerHTML = totalSeconds;
}
//to get the current conter value
function getTime() {
valueLabel.innerHTML = totalSeconds;
}
<label id="counter"></label>
<button onclick="getTime()">save</button>
<label id="value"></label>
Fiddle:
https://jsfiddle.net/871t3w2o/3/
You can also have a look into localstorage and sessionstorage they both work like the cookie but each one has it own advantages and disadvantages and you should choose the one that satisfy your need

Converting a JavaScript Countdown to a jQuery Countdown and adding an Interval

I found this JS-Countdown Script at JSFiddle.
EDIT:
I'm using the code of rafaelcastrocouto now, which is nearly perfect. I wanted a 10-seconds JQuery Countdown-Script with an interval that resets the countdown timer at 5 seconds and starts over again and again, but only for a specific class with a specific id on the whole HTML page. If it drops to 0, the countdown should stop. Also I want to reset specific counters to 10.
It's about a WebSocket that refreshes every second and depending on the data I get for specific counters I want to reset them or they should count down to zero.
New JSFiddle: http://jsfiddle.net/alexiovay/azkdry0w/4/
This is how I solved with jquery and native setInterval...
var setup = function(){
$('.count').each(eachSetup);
};
var eachSetup = function(){
var count = $(this);
var sec = count.data('seconds') ;
count.data('count', sec);
};
var everySecond = function(){
$('.count').each(eachCount);
};
var eachCount = function(){
var count = $(this);
var s = count.data('count');
count.text(s);
s--;
if(s < 0) {
s = count.data('seconds');
}
count.data('count', s);
};
setup();
setInterval(everySecond, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="count" data-seconds="5"></p>
<p class="count" data-seconds="10"></p>
<p class="count" data-seconds="15"></p>
You have sever errors in code, e.g.
setTimeout(cd_go(id), 1000); - should point to function reference not to function execution. setTimeout also returns the timeout id. You must past that id to clearTimeout
clearTimeout(this); it should take id instead of global object (window) or undefined if you are working in strict mode
loop = setInterval(function(id) { … } - id points to undefinded as you are not passing any value for it

Auto refresh a page with count down time

I have a small C# code behind to refresh a webform page (form.aspx) after 15 seconds as below:
lblMessage.Text = "<b><h2>Thank you!</h2></b></br>We will be right with you.<br><br><br>(This page will be refreshed automatically after 15 seconds)";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Success!", "setInterval(function(){location.href='/form.aspx';},15000);", true);
Right now the page will be refreshed after 15 seconds. How do I also make the timer count down every second? i.e., 15 => 14 => 13 => ... 1 then refresh so it will be better for users, they will know what is going on with the page...
In javascript I would go with something like this.
<div id='countdown'></div.
var countDown = 15;
function countdown() {
setInterval(function () {
if (countDown == 0) {
return;
}
countDown--;
document.getElementById('countdown').innerHTML = countDown;
return countDown;
}, 1000);
}
countdown();
Fiddle: http://jsfiddle.net/chzzcosy/
"<b><h2>Thank you!</h2></b></br>We will be right with you.<br><br><br>(This page will be refreshed automatically after <span id='counter'>15</span> seconds)"
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Success!", "setTimeout(function(){location.href='/form.aspx';},15000); counter = 15; setInterval(function(){counter--; document.getElementById('counter').innerHTML = counter;},1000);", true);
Should do it.
If added a span with id counter around the refresh message number.
Then I added counter = 15; to initialize a default value of 15. And another setInterval to the script block firing every second. With each pass it subtracts one from counter and updates the span with the new counter value. Users should now see the page counting down. I also changed the first setInterval to setTimout, since it's technically a timeout and not an interval that should occur every 15 seconds.

How to show last 5 seconds when timing is running out?

Hi i am using Javascript set timeout to run a certain function.
How do i display the last 10 seconds of the timeout when it is nearing the end?
var a = setTimeout('someFunction()', 10000);
Is it able to display something using the value that it store into the variable?
Thanks
I have created a small demo for you,
http://jsfiddle.net/praveen_prasad/DYaan/1/
<div id="target" style="display:none">
target
</div>
var target,
allotedTimeForWork=100 /*you can change this*/
;
var handler = setTimeout(function(){
if(!target)
{
target=document.getElementById('target');
}
target.style.display="block";
startTicker();
}, allotedTimeForWork);
function startTicker()
{
var counter=10;
var tickerHandler= window.setInterval(function(){
if(counter>0)
{
//cache target
target.innerHTML="you have "+counter +" seconds left";
counter--;
}
else
{
target.innerHTML="time over";
clearInterval(tickerHandler);
}
},1000);
}
It is not possible to directly get the remaining time of a Timeout.
You could either try to make multiple Timeouts for every second, or have another variable where you store when the Timeout was started.
I would use two timeouts.
The first with time minus 5 seconds, that calls a function with the second timeout (5 seconds) which would have the timer displayed.
Take a look here: http://jsfiddle.net/VCAnm/
HTML:
<span id="aaa">10</span>
JavaScript:
setInterval(function() {
var elem = document.getElementById('aaa');
elem.innerHTML = elem.innerHTML - 1;
}, 1000);
set 2 timers one for the timeout and another for the warning
var warn_time = 5000;
var function_name = 'someFunction()';
var a = setTimeout('warnFunction(function_name, warn_time)', 10000 - warn_time);
function warnFunction(function_name, time) {
alert('only ' + time + ' seconds left'); //use a div or whatever to display
var b = setTimeout(function_name, time);
}

Categories

Resources