Activate radio buttons on server time - javascript

<script language="javascript" type="text/javascript">
if (new Date().getHours() < 11)
{
document.getElementById("r1").checked = true;
} else if (new Date().getHours() < 16)
{
document.getElementById("r1").disabled = true;
document.getElementById("r2").checked;
}
else if (new Date().getHours() < 21)
{
document.getElementById("r1").disabled=true;
document.getElementById("r2").disabled=true;
document.getElementById("r3").checked;
}
</script>
<label class="label_radio" for="radio-01">
<input name="bdw" id="r1" type="radio"/>11:00 AM
<input name="bdw" id="r2" type="radio"/>4:00 PM
<input name="bdw" id="r3" type="radio"/>9:00 PM
</label>
how can i deactivate radio buttons base on the time as specified on my script? it looks like the one stated on the sample from the other part of this tutorial but it does not work. Am i lacking something?

Instead of using var date = new Date(); or var hours = date.getHours(); . you should use PHP to store time in a variable and than compare time from that variable. As JS track the client side time so comparing using JS time can be easily tricked if someone changes his computer-system time.
hours = <?php echo date("h"); ?>
hours+=1;
if(hours>23){
hours = 0;
}

It works, but you didn't set the values of checked to true. The default value of .checked is false. And you didn't disable the other radio buttons.
Check it out here: https://jsfiddle.net/qsuxp12h/
var date = new Date();
//var hours = date.getHours();
var hours = 10; // <- Mess around to test it
if (hours < 11) {
document.getElementById("r2").disabled = true;
document.getElementById("r3").disabled = true;
document.getElementById("r1").checked = true;
} else if (hours < 16) {
document.getElementById("r1").disabled = true;
document.getElementById("r3").disabled = true;
document.getElementById("r2").checked = true;
} else if (hours < 21) {
document.getElementById("r1").disabled = true;
document.getElementById("r2").disabled = true;
document.getElementById("r3").checked = true;
}

You are executing the script before the code is loaded so script should be done after page load.
<label class="label_radio" for="radio-01">
<input name="bdw" id="r1" type="radio"/>11:00 AM
<input name="bdw" id="r2" type="radio"/>4:00 PM
<input name="bdw" id="r3" type="radio"/>9:00 PM
</label>
<script language="javascript" type="text/javascript">
current_time = new Date().getHours();
if (current_time < 11)
{
document.getElementById("r1").checked = true;
} else if (current_time < 16)
{
document.getElementById("r1").disabled = true;
document.getElementById("r2").checked = true;
}
else if ( current_time < 21)
{
document.getElementById("r1").disabled=true;
document.getElementById("r2").disabled=true;
document.getElementById("r3").checked = true;
}
</script>

Related

Make the output of a span the value of an input

Good day all, i am building a form that uses javascript to get a client's local time which is correctly displayed in span element. However i wish to make the output of the span element the value of an input field in order to pass same into mysql. I tried php like below, it rather displays the code.
$currenttradetime = "<span id='digital-clock'></span>";
$currenttt = $currenttradetime;
?>
<input type='hidden' name="time" value="<?php echo $currenttt; ?>"></span>'>
Then using html/php, it equally displays the span html codes rather than the time. How do i achieve this?
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
month = '0'+month;
}
if(day.toString().length == 1) {
day = '0'+day;
}
if(hour.toString().length == 1) {
hour = '0'+hour;
}
if(minute.toString().length == 1) {
minute = '0'+minute;
}
if(second.toString().length == 1) {
second = '0'+second;
}
var dateTime = hour+':'+minute+':'+second;
return dateTime;
}
// example usage: realtime clock
setInterval(function(){
currentTime = getDateTime();
document.getElementById("digital-clock").innerHTML = currentTime;
}, 1000);
The time is: <span id='digital-clock'></span>
<input type='text' value='<span id="digital-clock"></span>'>
Just use JavaScript to set the value of the input field like so:
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
month = '0'+month;
}
if(day.toString().length == 1) {
day = '0'+day;
}
if(hour.toString().length == 1) {
hour = '0'+hour;
}
if(minute.toString().length == 1) {
minute = '0'+minute;
}
if(second.toString().length == 1) {
second = '0'+second;
}
var dateTime = hour+':'+minute+':'+second;
return dateTime;
}
// example usage: realtime clock
setInterval(function(){
currentTime = getDateTime();
document.getElementById("digital-clock").innerHTML = currentTime;
document.getElementById('time').value = currentTime;
}, 1000);
<span id="digital-clock"></span>
<input id="time" />
Change
<input type='hidden' name="time" value="<?php echo $currenttt; ?>"></span>'>
to have an id too and do not set the html as value for the input field:
<input id='digital-clock-inputfield' type='hidden' name="time" value=""></span>'>
then change
document.getElementById("digital-clock").innerHTML = currentTime;
to set the value of the input field too:
document.getElementById("digital-clock").innerHTML = currentTime;
document.getElementById("digital-clock-inputfield").value = currentTime;

multiple alarm clock in javascript using dynamic generated input elements in javascript

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>

How to separate regex in javascript Hours format

I have some problem to define hours time, i want to separate hours time to 3 time type morning, evening, and night.
if time start from 00:00 to 10:00 the type time is morning,
if time start from 10:01 to 18:00 the type time is evening,
if time start from 18:01 to 23:59 the type time is night,
i have code jquery like this
$(document).ready(function(){
$('#submit').on('click',function(){
var hrs=$('#hours').val();
var nm=$('#scedule').val();
var patt = new RegExp("^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$");
var patts = patt.test(hrs);
//morning = 00:00 - 10:00
var morn = new RegExp("^([0-9]|0[0-9]|1[0-9]):[0-5][0-9]$");
var morning = morn.test(hrs);
//evening = 10:01 - 18:00
var even = new RegExp("^(1[0-9]|[0-9]):[0-5][0-9]$");
var evening = even.test(hrs);
//night = 18:01 - 00:00
var nig = new RegExp("^(1[0-9]|2[0-3]):[0-5][0-9]$");
var night = nig.test(hrs);
if ( patts == morning ) {
alert('This is Morning');
} else if (patts == evening){
alert('This is Evening');
} else if (patts == night){
alert('This is night');
} else {
alert('Format is wrong');
}
});
});
and this is my form HTML :
Scedule : <input type="text" id="scedule"><br>
Time : <input type="text" id="hours"><br>
<input type="submit" value="submit" id="submit"><br>
You don't need a regex here, just use Date:
$(document).ready(function(){
$('#submit').on('click',function(){
var hrs=$('#hours').val();
if(hrs.length != 5 || hrs.indexOf(':') < 0)
{
alert("Wrong Fromat")
return;
}
var date = new Date();
date.setHours(hrs.split(":")[0]);
date.setMinutes(hrs.split(":")[1]);
console.log(date)
if ( date.getHours() < 10) {
console.log('This is Morning');
} else if (date.getHours() > 18 && date.getMinutes > 0){
console.log('This is night');
} else{
console.log('This is Evening');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
Time : <input type="text" id="hours"><br>
<input type="submit" value="submit" id="submit"><br>

(JS) Enable Button during a certain period of time in a day

I've been trying to enable a button only in a certain period of time in a day, but I can't make it work..
What I've been trying to do:
The button should be enabled from 17:00 o'clock to 22:00 o'clock (GMT +1).
I wrote my script with the aid of sites where people were requesting a similar system, but I can't make it work.. I hope that you can help me
Sorry for my english^^
Here is the script:
<input class="submit" type="submit" id="checktime" value="Check"/>
<script type="text/javascript" defer="defer">
<!--
var enableDisable = function(){
var UTC_hours = new Date().getUTCHours() +1;
if ((UTC_hours == 17) && (UTC_hours == 18) && (UTC_hours == 19) && (UTC_hours == 20) && (UTC_hours == 21) && (UTC_hours == 22)){
document.getElementById('checktime').disabled = false;
else
document.getElementById('checktime').disabled = true;
}
setInterval(enableDisable, 1000*60);
enableDisable();
// -->
</script>
You had missing brackets and your id was wrong, this should work.
<input class="submit" type="submit" id="checktime" value="Check"/>
<script type="text/javascript" defer="defer">
<!--
var enableDisable = function(){
var UTC_hours = new Date().getUTCHours() +1;
if (UTC_hours > 16 && UTC_hours < 22){
document.getElementById('checktime').disabled = false;
}
else
{
document.getElementById('checktime').disabled = true;
}
};
setInterval(enableDisable, 1000*60);
enableDisable();
// -->
</script>
The if statement isn't going to work like that; you're testing if the hour is 17 AND 18 AND 19 AND..., which is obviously never going to be the case as it can't be all of those hours at once. It should be:
if (UTC_hours > 16 && UTC_hours < 22)
That will ensure that it's at least 5pm, but before 10pm.

Enable Button during certain day & time

I am trying to enable a button ONLY during 5PM to 10PM every day, except Monday.
When the button is disabled, <p></p> should show up (like a notification to the visitor why it is disabled.)
I did try to write the JavaScript on my own, but it seem not to work correctly. I don't know anything about that language and did the script with aid of different sites.
Here is my script:
<input class="submit" type="submit" id="checktimer" value="Check"/>
<p id=timer style="display: none;">Lorem ipsum</p>
<script type="text/javascript" defer="defer">
<!--
var enableDisable = function(){
var UTC_hours = new Date().getUTCHours() +1;
var day = new Date().getDay();
if (day == 1){
document.getElementById('checktimer').disabled = true;
document.getElementById('timer').style.display = 'block';
}
else{
if (UTC_hours > 16 && UTC_hours < 22){
document.getElementById('checktimer').disabled = false;
document.getElementById('timer').style.display = 'none';
}
else
{
document.getElementById('checktimer').disabled = true;
document.getElementById('timer').style.display = 'block';
}
}
};
setInterval(enableDisable, 1000*60);
enableDisable();
// -->
</script>
This would work:
var enableDisable = function(){
var UTC_hours = new Date().getUTCHours(); //Don't add 1 here
var day = new Date().getUTCDay(); //Use UTC here also
if (day != 1 && UTC_hours >= 17 && UTC_hours < 22){
document.getElementById('checktimer').disabled = false;
document.getElementById('timer').style.display = 'none';
}else{
document.getElementById('checktimer').disabled = true;
document.getElementById('timer').style.display = 'block';
}
};
setInterval(enableDisable, 1000*60);
enableDisable();
Cheers
DEMO
Try setting the attribute on the element, instead of a property on the element object:
document.getElementById('checktimer').setAttribute('disabled');
To remove it, use
document.getElementById('checktimer').removeAttribute('disabled');
As others have mentioned, you should cache the checktimer element in a variable, instead of looking it up each time.
A couple of other minor things I changed:
Removed those Javascript comment things you had. You don't need those.
Added quotes around the value of the id attribute for your p element.
Actually, you shouldn't enable or disable the button based on JavaScript DateTime because it gets the client machine's date, meaning that if the user changes it's system date the button will be enabled. You should verify it on the server-side code, such as PHP or ASP. There, you can check for datetime validation, and write the button on the page, or not.
Just get rid of the HTML comment <!-- or comment it with //
<script type="text/javascript">
//<!--
var enableDisable = function(){
var UTC_hours = new Date().getUTCHours() +1;
var day = new Date().getDay();
if (day == 1){
document.getElementById('checktimer').disabled = true;
document.getElementById('timer').style.display = 'block';
}
else{
if (UTC_hours > 16 && UTC_hours < 22){
document.getElementById('checktimer').disabled = false;
document.getElementById('timer').style.display = 'none';
}
else
{
document.getElementById('checktimer').disabled = true;
document.getElementById('timer').style.display = 'block';
}
}
};
setInterval(enableDisable, 1000*60);
enableDisable();
// -->
</script>
Your script should then work normally

Categories

Resources