Reputation: 23
The following code is supposed to display a confirmation box. if the user clicks the ok button, the current time is supposed to be displayed. But for some reason when I test the button by clicking on it nothing happens. I need a fresh pair of eyes to tell me what I'm missing as to why this code isn't working. Thank you for your help:
<script>
function confirmationDemo() {
var ok = confirm("Click OK to show the time, \n or click Cancel to close this window \n
without doing anything.");
var now = new Date();
var hour;
var minute;
if (now.getHours() < 12) {
hour = now.getHours();
} else {
hour = now.getHours() - 12;
}
if (now.getMinutes() < 10) {
minute = "0" + now.getMinutes();
} else {
minute = now.getMinutes();
}
if (ok == true && now.getHours() < 12) {
document.getElementById("confirmationDemoReturn").innerHTML = "The time is: " + hour +
":" + minute + " am.";
} else {
document.getElementById("confirmationDemoReturn").innerHTML = "The time is: " + hour +
":" + minute + " pm.";
}
}
</script>
Try it: <input type="button" value = "Confirmation Box" onClick =
"confirmationDemo();">
<p id="confirmationDemoReturn"></p>
Upvotes: 1
Views: 3710
Reputation: 56529
The problem seems to be too simple, the text within the confirmation is not properly concatenated. Hence it was not working.
var ok = confirm("Click OK to show the time, \n or click Cancel to close this window \n
//--- an enter key is pressed
without doing anything.");
I have tested in fiddle
Upvotes: 1
Reputation: 103
First of all, you should not set events in HTML but in JS. HTML is there for structure, not for interaction. However, if you want to use this method, you have to add the following meta tag in the header of you document:
<meta http-equiv="Content-Script-Type" content="text/javascript">
However, I recommend adding the event in JavaScript like this:
var button = document.getElementById('btn');
button.onclick = confirmationDemo;
Of course after setting an id for your input:
<p id="confirmationDemoReturn"></p>
Check out this Fiddle: http://jsfiddle.net/R5t6z/
Upvotes: 0