nothing happens when clicking button to call javascript function - javascript

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>

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

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/

Related

How to detect a button press with Gamepad API?

I am trying to write a web page where I can detect button presses on a Xbox controller and show a user a boolean value based on the button pressed. Right now, I can detect a controller being connected and show that as a string. The documentation says to use this code to detect a button press here:
var isPressed = navigator.getGamepads()[0].pressed;
but Chrome shows this error when using it:
Uncaught TypeError: Cannot read property 'pressed' of null
The error is linked to the .pressed part of the above line of code. All the documentation is on the Mozilla site, so I'm assuming they used FireFox when writing the tutorials.
What I ideally want to end up with is this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<h id="button"></h>
<h id="gpInfo"></h>
<script>
var i = 1;
window.addEventListener("gamepadconnected", function(e) {
var gp = navigator.getGamepads()[e.gamepad.index];
document.getElementById("gpInfo").innerHTML = ("A " + gp.id + " was successfully detected! There are a total of " + gp.buttons.length + " buttons.")
//alert("A " + gp.id + " was successfully detected!")
});
var isPressed = navigator.getGamepads()[0].pressed;
document.getElementById("button").innerHTML = isPressed;
</script>
<!-- <script type="text/javascript" src="gamepadtest.js"></script> -->
</head>
</html>
The code would print a boolean value on the screen for users to see when they press a button.
This is my first time working with JavaScript and HTML. If you could make your answer noob-friendly that would be great! Documentation for Gamepad API and for GamepadButton
You shouldn't reference the Gamepad object until the gamepadconnected event has been thrown. Also, you'll need a loop to poll the button value. Here's some revised code:
var i = 1;
window.addEventListener("gamepadconnected", function(e) {
var gp = navigator.getGamepads()[e.gamepad.index];
document.getElementById("gpInfo").innerHTML = ("A " + gp.id + " was successfully detected! There are a total of " + gp.buttons.length + " buttons.")
//alert("A " + gp.id + " was successfully detected!")
setInterval(function(){
isPressed = gp.buttons[0].pressed;
document.getElementById("button").innerHTML = isPressed;
}, 100)
});
I don't have enough reputation to just add a comment to Caleb Denio's answer, but regarding Nathan's comment on that answer:
I have used your example to listen for 20 buttons and i can detect each button, but once i have pressed one, it will not change another result for a different button.
I see the same behaviour on Chrome 90. Specifically, a new GamepadList instance, containing new Gamepad instances, all seem to be created each time the state of any gamepad changes (e.g. which of its buttons are pressed).
You can test it with this:
var gamepads = null;
function callback() {
var new_gamepads = navigator.getGamepads();
if(new_gamepads !== gamepads) {
console.log('New GamepadList!', new_gamepads);
gamepads = new_gamepads;
}
}
var interval = setInterval(callback, 100);
...for me, that logs 'New GamepadList!' each time I press/release a button.
Long story short, you need to poll navigator.getGamepads() each frame in order to detect changes in gamepad state.
A minimalist fix for Caleb Denio's answer would therefore be:
var i = 1;
window.addEventListener("gamepadconnected", function(e) {
var gp = navigator.getGamepads()[e.gamepad.index];
document.getElementById("gpInfo").innerHTML = ("A " + gp.id + " was successfully detected! There are a total of " + gp.buttons.length + " buttons.")
//alert("A " + gp.id + " was successfully detected!")
setInterval(function(){
// ===> Get a fresh GamepadList! <===
var gp = navigator.getGamepads()[e.gamepad.index];
isPressed = gp.buttons[0].pressed;
document.getElementById("button").innerHTML = isPressed;
}, 100)
});

Previous selected date doesn't get unselected in calendar

So I only want to have one selected date on my calendar UI, however when I press a new date, the old one is still lit up, and so I can press all the days on my calendar and they'll all light up.
for(var dayCounter = 1; dayCounter <= currMonthDays; dayCounter++){
tempListItem = document.createElement("li");
tempListItem.innerHTML = dayCounter;
$(tempListItem).addClass("day");
//add a hidden element to the day that we can access when we click on it
var temp = months[currMonth] +"/" + dayCounter +"/" + currFullYear;
$(tempListItem).append("<div class = 'hidden'>" + temp + "</div>");
if(dayCounter == date.getDate() && currMonth == date.getMonth()){
tempListItem.setAttribute("id", "current-day");
}
ulDays.appendChild(tempListItem);
}
$(document).on("click", ".day", function()
{
var date = $(this).children(".hidden").text();
console.log(date);
$(document.getElementById("current-day")).removeAttr("#current-day");
$(this).attr("id", "current-day");
});
After removing the current-day class, shouldn't the element lose its CSS?
It looks like you have a small big when you try to remove the id from the current-day. removeAttr expects the name of an attribute. In this case, that attribute would be id, so try this:
$(document.getElementById("current-day")).removeAttr("id");

Show alert box once when going to a page

I have here a code that every time the page reloads an alert will pop up. But I want the alert box to pop up once. For example, whenever I open that page an alert will pop up but if I reload that page, there will be no alert box that will pop up. Anyone knows how I can do that?
Here's my code for the alert box:
<script type="text/javascript">
window.onload = function () {
alert("Sending of SMS is scheduled TODAY!");
//dom not only ready, but everything is loaded
}
</script>
Thanks for the help in advance.
Do as below:
<script type="text/javascript">
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var today = year + "/" + month + "/" + day;
window.onload = function () {
var item = localStorage.getItem("alertShown_"+today);
if ( item === null || item != "Yes") {
//check if localStorage has value or it is == "Yes"
alert("Sending of SMS is scheduled TODAY!");
localStorage.setItem("alertShown_"+today,"Yes"); //set some value for future check
}
}
</script>

Javascript Default Values reset on page reload

I am new to the javascript/aspx world and most of my programming was done through trial and error and lots of internet searching, but i've hit upon a problem i cannot find a solution for.
I have a popup page that has 2 input boxes, and i have managed to add default values to both of these input boxes, for dates, like so:
$(window).load(function () {
var now = new Date();
var month = (now.getMonth() + 1);
var day = now.getDate();
if (month < 10)
month = "0" + month;
if (day < 10)
day = "0" + day;
$('#FNewDate').val('01/' + month + '/' + now.getFullYear());
$('#TNewDate').val(day + '/' + month + '/' + now.getFullYear());
}
now, if the user has entered a new date and hits the submit button, the page posts and reloads with the calculated results displayed to the user AND THE DEFAULT VALUES again, but not with the new dates the user has entered, and i need it to stay with the entered information.
I have tried playing around with static members but i have not been able to get it to work.
Here is the button action:
<asp:Button ID = "Calculate" runat = "server"
style="width:40% ; font:15px arial" Text = "Calculate" onclick="Calculate_Click" />
any help on the above would be appreciated, and pls include code in your replies...
Thnks
You should change your default value setters to add
if ($('#FNewDate').val().length() != 0)
To only set the value in case the value coming from server is empty.
Then in your input
<input type="text" id="FNewDate" value="<%=someObject.getSomeDate()%>"/>

Multiple Timer Javascript

I have a page where I want show multiple countdowns. I made a javascript code that makes the countdown and it works on all divs that i specify, but this goes in real time only on the last div. Can someone help me? I posted the page below.
<html>
<head>
<title>Timer</title>
<head>
<script type="text/javascript">
function Timer(){
this.countdown=function(fineanno, finemese, finegiorno, fineore, fineminuti, finesecondi, nomediv)
{
var_div=nomediv;
var_anno=fineanno;
var_mese=finemese;
var_giorno=finegiorno;
var_ore=fineore;
var_minuti=fineminuti;
var_secondi=finesecondi;
data_scandeza= new Date(var_anno,var_mese-1,var_giorno,var_ore,var_minuti,var_secondi);
data_oggi= new Date();
differenza=(data_scandeza-data_oggi);
giorni=parseInt(differenza/86400000);
differenza=differenza-(giorni*86400000);
ore=parseInt(differenza/3600000);
differenza=differenza-(ore*3600000);
minuti=parseInt(differenza/60000);
differenza=differenza-(minuti*60000);
secondi=parseInt(differenza/1000);
differenza=differenza-(secondi*1000);
if (giorni <= "0" && ore <= "0" && minuti <= "0" && secondi <= "0")
{
document.getElementById(nomediv).innerHTML="Tempo scaduto";
}
else
{
document.getElementById(nomediv).innerHTML=giorni +' giorni '+ore+' ore '+minuti+' min '+secondi+' sec';
setTimeout("t"+var_div+".countdown(var_anno, var_mese, var_giorno, var_ore, var_minuti, var_secondi, var_div)",1000);
}
}
}
</script>
</head>
<body>
<div id="div2"></div>
<script>
var tdiv2 = new Timer();
tdiv2.countdown("2013","04","26", "23","00","00","div2");
</script>
<div id="div3"></div>
<script>
var tdiv3 = new Timer();
tdiv3.countdown("2013","04","26", "23","00","00","div3");
</script>
</body>
</html>
var_div, var_anno, var_mese, var_giorno, var_ore, var_minuti and var_secondi are global variables, because you declared them without using the var keyword. That means all your calls to countdown will access the same variable.
Don't use the name of the variable in your setTimeout, or you'll get the current value of this global variable (the second one set). Instead, use the value of the variable at the time you build the settimeout, like this:
setTimeout("t"+var_div+".countdown(" + var_anno + ", " + var_mese + ", " + var_giorno + ", " + var_ore + ", " + var_minuti + ", " + var_secondi + ",'" + var_div + "')",1000);
In fact I don't see any need for this part at all:
var_div=nomediv;
var_anno=fineanno;
var_mese=finemese;
var_giorno=finegiorno;
var_ore=fineore;
var_minuti=fineminuti;
var_secondi=finesecondi;
Instead of using those new variables, you can just use the parameters that were passed in. I suppose the reason you had that is so the setTimeout would have a variable to read the value from, but with my suggested change above it is no longer necessary.

Categories

Resources