I’m new to JavaScript. I have an HTML file with a button, I would need to call the following JS when a button is clicked. Any idea how to do it <input type="submit" value="Get Push Token" />?
Please provide me a sample of code.
PushToken.getToken(
["getToken"] ,
function(token) {
global.token = token;
},
function(error) {
console.log("Error : \r\n"+error);
}
);
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name = "format-detection" content = "telephone=no"/>
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width;" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello Cordova</title>
</head>
<body>
<div class="app">
<h1>Apache Cordova™</h1>
<div id="deviceready">
<p class="status pending blink">Connecting to Device</p>
<p class="status complete blink hide">Device is Ready</p>
<p>Click here to get the Token<input type="submit" value="Get Push Token" />
</div>
</div>
<script type="text/javascript" src="cordova-2.0.0.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/PushToken.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
Without Using jQuery
In a simple component or application, you wouldn’t want to require the entire jQuery library, so the simplest way to do it would be like this:
HTML:
JavaScript:
Using jQuery
If you’re building a complex application, there’s a good chance you’ll be wanting jQuery for something else, in which case you may as well do it like this:
HTML:
JavaScript:
Understanding what’s going on
In either case, the key point is that you wrap the code you want to execute in a function, and set it as the handler of the click event for that button. The button will then cause the function to be called.
Using the correct HTML
If the button is not within a form, you should probably use:
for the html instead, the JavaScript would be exactly the same.