Reputation: 233
On a page, Save button should be visible or hidden based on system time. I want to hide Save button everyday after 10 AM. My broken code
<script type="text/javascript">
var currentTime = new Date();
var hours = currentTime.getHours();
var newButton = document.getElementById("btn1");
if(hours>10) {
newButton.style.display = "none";
//tried this one too
// document.getElementById('btn1').style.visibility = 'hidden';
}
else {
newButton.style.display = "block";
}
</script>
In HTML code I added
<input id="btn1" type="button" value="Save" name="btnSave" onclick="javascript: {ddwrt:GenFireServerEvent('__commit')}" />
Any suggestion or help.
Upvotes: 3
Views: 3172
Reputation: 13304
Wrap it in a onload event. Your button isn't on the page yet. An element that isn't rendered yet cannot be addressed.
window.addEventListener("load", function(){
var currentTime = new Date();
var hours = currentTime.getHours();
var newButton = document.getElementById("btn1");
if(hours>10) {
newButton.style.display = "none";
}
else {
newButton.style.display = "block";
}
}, false);
This way it fires when the page is loaded and the button in question is present.
Or like Deef commented, put the script tag on the bottom of your page.
Upvotes: 0
Reputation: 147363
Your function can be really simple, e.g.:
window.addEventListener("load", function(){
var newButton = document.getElementById("btn1");
newButton.style.visibility = new Date().getHours() > 10? 'none' : '';
});
Note that the default display value for buttons is inline-block
, but not all browsers will necessarily use that and CSS may be used to set it to some other value. Setting the display to "" (empty string) lets it adopt its default or inherited style for the particular browser or style sheet and you don't have to change your code very time the page designer changes her/his mind.
Also, to really disable the button, you should set it's disabled property to true.
Upvotes: 1