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:
<input type="submit" value="Get Push Token" id="getPushToken" />
JavaScript:
document.getElementById('getPushToken').onclick=function(){
PushToken.getToken(
["getToken"] ,
function(token) {
global.token = token;
},
function(error) {
console.log("Error : \r\n"+error);
}
);
}
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:
<input type="submit" value="Get Push Token" id="getPushToken" />
JavaScript:
$('#getPushToken').click(function(){
PushToken.getToken(
["getToken"] ,
function(token) {
global.token = token;
},
function(error) {
console.log("Error : \r\n"+error);
}
);
});
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:
<button id="getPushToken">Get Push Token</button>
for the html instead, the JavaScript would be exactly the same.
HTML:
<input type="submit" value="Get Push Token" id="getPushToken" />
JavaScript:
document.getElementById('getPushToken').onclick=function(){
PushToken.getToken(
["getToken"] ,
function(token) {
global.token = token;
},
function(error) {
console.log("Error : \r\n"+error);
}
);
}
Anyway you have an input with type="submit", but you haven't any form, that's a bit nonsense.
If you just want a button, use type="button". If you want to submit a form, create a form which contains that input and whose id is, for example, myform. Then,
document.getElementById('myform').onsubmit=function(){
PushToken.getToken(
["getToken"] ,
function(token) {
global.token = token;
},
function(error) {
console.log("Error : \r\n"+error);
}
);
}
...
Put the code inside an event handling function, and then call that function in the onclick of the button.
HTML:
/* you probably want button, not submit, and it should have an ID */
<input type="button" id="someID" value="Get Push Token" />
JS:
document.getElementById('someID').onclick = function () {
// whatever you want to do here
};
Note that there are other ways to bind event handlers, but this is considered the best practice (keep javascript and HTML separated)
Related question: JavasScript event handling best practice?
Related
Good Afternoon,
I want to set a localStorage to another domain. I used the postMessage function.
Here is the parent page :
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script>
var childwin;
const childname = "popup";
function openChild() {
childwin = window.open('Page2.html', childname, 'height=300px, width=500px');
}
function sendMessage(){
let msg={pName : "Bob", pAge: "35"};
// In production, DO NOT use '*', use toe target domain
childwin.postMessage(msg,'*')// childwin is the targetWindow
childwin.focus();
}
</script>
</head>
<body>
<form>
<fieldset>
<input type='button' id='btnopen' value='Open child' onclick='openChild();' />
<input type='button' id='btnSendMsg' value='Send Message' onclick='sendMessage();' />
</fieldset>
</form>
</body>
</html>
Here the children :
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script>
// Allow window to listen for a postMessage
window.addEventListener("message", (event)=>{
// Normally you would check event.origin
// To verify the targetOrigin matches
// this window's domain
let txt=document.querySelector('#txtMsg');
localStorage.setItem("age", event.data.pAge);
// event.data contains the message sent
txt.value=`Name is ${event.data.pName} Age is ${event.data.pAge}` ;
});
</script>
</head>
<body>
<form>
<h1>Recipient of postMessage</h1>
<fieldset>
<input type='text' id='txtMsg' />
</fieldset>
</form>
</body>
</html>
This works fine but we need 2 buttons. One to open the page, the other to post the message.
If I want to make the two methods openChild();postMessage() in the same button, it does not work.
I think it is because the page2.html is not totally loaded when we call postMessage().
How can we do ?
Best regards.
Christophe.
you can include your script when DOM loads
document.addEventListener('DOMContentLoaded', () => {
//do some functions
})
I can make the payments work for test cards NOT requiring 3DSecure authentication. For cards that require it, no modal pops up. In the dashboard the payments will show up with status "The customer must complete an additional authentication step." In these cases I don't even reach the
then(function(result) {
if (result.error) {
alert(result.error.message);
}
else {
alert('Success!');
code part. With non-3ds test cards, this part is working fine.
Debugging the javascript will show me some meaningless exceptions from stripe js script.
Given that it works for some cards, the server site initialization of the payment intent, and passing of the clientsecret, can be ruled out, that part works.
<head runat="server">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://js.stripe.com/v3/"></script>
<style type="text/css">
.auto-style1 {
width: 930px;
}
</style>
</head>
<form id="form1" runat="server">
<div>
<asp:HiddenField ID="hiddenClientSecret" runat="server" />
<input id="cardholder-name" type="text"/>
<!-- placeholder for Elements -->
<div id="card-element" class="auto-style1"></div>
<button id="card-button">
Submit Payment
</button>
</div>
</form>
<script >
var stripe = Stripe('mykey', {locale: 'en'});
var elements = stripe.elements({locale: 'en'});
var cardElement = elements.create('card', {hidePostalCode: true});
cardElement.mount('#card-element');
var cardholderName = document.getElementById('cardholder-name');
var cardButton = document.getElementById('card-button');
var clientSecret = document.getElementById('hiddenClientSecret').value;
cardButton.addEventListener('click', function(ev) {
stripe.handleCardPayment(
clientSecret, cardElement, {
payment_method_data: {
billing_details: {name: cardholderName.value}
}
}
).then(function(result) {
if (result.error) {
alert(result.error.message);
}
else {
alert('Success!');
}
});
});
</script>
OK, I needed to explicitly set button type to "button" - otherwise it does a submit roundtrip to the server: <button type="button" id="card-button">. That code part was taken directly from Stripe, seems they need to be a little more precise in their docs!
I'm trying to set up the DirectLineJS to work in a website just for testing purposes right now. I've built the DirectLineJS repo and added /built/directLine.js to my website folder following the documentation here https://github.com/Microsoft/BotFramework-DirectLineJS
In the HTML page I'm just using a button to try to send a message through the direct line
<html>
<head>
<meta charset="UTF-8" />
<title>Bot Chat</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://unpkg.com/botframework-directlinejs/directLine.js" type="javascript"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<style>
.wc-chatview-panel {
width: 320px;
height: 500px;
position: relative;
}
.h2 {
font-family: Segoe UI;
}
</style>
</head>
<body>
<h2 style="font-family:Segoe UI;">Welcome to my custom Bot!</h2>
<section class="container">
<input id="clickMe" type="button" value="clickme" onclick="connectDirectLine();" />
</section>
<textarea id="myTextarea">
342 Alvin Road
Ducksburg</textarea>
<p>Click the button to change the contents of the text area.</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var text = document.getElementById("myTextarea").value;
console.log(text)
}
</script></body>
</html>
<script>
function connectDirectLine() {
import { DirectLine } from 'botframework-directlinejs';
var directLine = new DirectLine({
secret: "mySecret",
});
directLine.postActivity({
from: { id: 'myUserId', name: 'myUserName' }, // required (from.name is optional)
type: 'message',
text: 'a message for you, Rudy'
}).subscribe(
id => console.log("Posted activity, assigned ID ", id),
error => console.log("Error posting activity", error)
);
directLine.activity$
.filter(activity => activity.type === 'message' && activity.from.id === 'yourBotHandle')
.subscribe(
message => console.log("received message ", message)
);
}
</script>
<html
When I run the website the error I'm getting is unexpected token import from import { DirectLine } from "botframework-directlinejs";
how can I properly import the botframework-directlinejs file so that I can use the DirectLine object?
You are mixing TypeScript with JavaScript.
To use Direct Line add the following to the HTML of your page:
<script src="http://unpkg.com/botframework-directlinejs/directLine.js"/>
Then you should delete your Import statement and finally, update the code that creates the DirectLine object to be:
var directLine = new DirectLine.DirectLine({
secret: "mySecret",
});
Notice the DirectLine.DirectLine
I am new to javascript programming so am hoping that this is a simple issue... I'm wanting my webpage to allow a user to input a music track name and artist in two separate fields and once you hit 'go' the javascript will run and parse the input into a string. To test I have tried to see if these inputs are being taken and I have tried to print them to console, however nothing is being printed to the console.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Spotify</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main class="main-container">
<div class="header">
<p>TrackSelector</p>
</div>
<section>
<div class="form">
<form action="">
<input type="textt" class="track" placeholder="Enter track..." />
<input type="texta" class="artist" placeholder="Enter artist..." />
<button type="button" class="submit-btn">GO</button>
</form>
</div>
</section>
</main>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
Javascript file:
const app = {};
//Allow the user to enter names
app.events = function() {
$('form').on('button', function(e){
e.preventDefault();
let tracks = $('input[type=textt]').val();
let artists = $('input[type=texta]').val();
console.log(tracks);
console.log(artists);
});
};
//
//
app.init = function(){
app.events();
};
$(app.init);
I believe I have specified to take in the correct inputs and specified the correct button reference, have played around to try out other methods but I'm still quite stuck... any ideas?
Replace
$('form').on('button', function(e){
with
$('form .submit-btn').on('click', function(e){
jQuery .on() expects event name as its first argument.
There is no input type type="textt" and texta. There are only predefined types like text, email, password, checkbox and so on... So make type "text" in both inputs and for reference use id: <input id="my_track" type="text">. Then in javascript get value by $('#my_track').val(); To handle submit use $('form').on('submit', func)
I am trying to place some Javascript code inside a .js file so that I can call it from multiple HTML pages. The problem is, my Javascript code works fine if I place it in a script within the HTML page, but when placed in a external .js file, it simply does not work. I've looked at these questions quite a few times and still cannot find the error.
Here's the HTML page:
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/global.css" />
<link rel="stylesheet" type="text/css" href="css/contacts.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src ="js/contactsModule.js"></script>
<title>Hall of Heroes</title>
</head>
<body onload = "contactsModule.getContacts();">
<!-- Global Header Starts Here -->
<div class="header">
<div class="cancel">
<img src="img/cancel.png" /><!-- if screen is triggered from onboarding, then go back to onboarding screen instead of home -->
</div>
<h1>My Contacts</h1>
</div>
<div class="wrapper">
<h3>A</h3> <!-- letter header goes here -->
<!-- Begin Contact Unit -->
<div class="feed">
</div>
<!-- End Contact Unit -->
</div>
</body>
</html>
And here is the .js file:
var contactsModule = (function($){
function getContacts()
{
dbContacts();
}
function displayContacts(contactArray){
window.alert('displayContacts now running!');
var jsonObject = $.parseJSON(contactArray);
jsonObject.forEach(function (dat) {
//Begin Contact Unit
$('.feed')
.append('<div class="feed-img"><img src="' + dat.avatarUrl + '"/>\
</div><div class="feed-text"><p><span class="name_highlight">\
' + dat.firstName + ' ' + dat.lastName + '</span></p></div>');
//End Contact Unit
});
}
function dbContacts() {
var avatarUrl;
var firstName;
var lastName;
$.ajax({
type: "GET",
url: "http://www.hallofheroesapp.com/php/contacts.php",
data: {avatarUrl: avatarUrl, firstName: firstName, lastName: lastName},
success: function (response) {
window.alert('AJAX ran successfully!');
displayContacts(response);
},
error: function(response){
alert("Error:" + response);
}
});
}
}(jQuery));
Thank you for your help!
You aren't returning anything from your IIFE. contactsModule will then not contain anything, ie equal undefined. Also just defining functions doesn't make those functions part of some object, with the exception of globally defined functions. You have to assign them, or define them as part of an object literal
Your code should be something like
var contactsModule = (function($){
return {
getContacts: function() {
/* code */
},
displayContacts: function(contactArray){
/* code */
}
dbContacts function() {
/* code */
}
};
}(jQuery));
How about using
$(document).ready(function(){
///// your code here...
});
... change ...
<body onload = "contactsModule.getContacts();">
... to ...
<body>
... and add event handler using jquery ...
(function($){
function getContacts()
{
dbContacts();
}
/* ... etc ... */
// use jquery's onready handler
$(getContacts);
}(jQuery));
Had the same problem. Easy thing when you research on google.
Your Js code loads before the DOM loads. Which should be the other way around. So you have to use this
$(document).ready(function(){
//only jQuery is recommended, global JavaScript functions outside!
});
Also JavaScript
document.addEventListener("DOMContentLoaded", function(event) {
//global function outside!
});
Only this way you can be sure that your DOM is loaded before your jquery finds your elements.