Calling JavaScript from component template - javascript

I'm working on integrating payment forms from a third party, by using the Link to Javascript they provide.
when I place the code in the index.html page its works just fine, but when I move the code to the component template is not working, below is part of the code:
this is the script code to initialize the payment form:
<script>
var tokenpay = TokenPay('tokenpay123');
tokenpay.initialize({
dataElement: 'card',
errorElement: 'errorMessage',
amountElement: 'amount',
useACH: false,
//if displaying all 4 fields then useStyles=false, disableZip=false, disableCvv=false
//if displaying 3 out of 4 fields then useStyles=false, and set disableZip or disableCvv equal to true
//if displaying 2 out of 4 fields then useStyles=true, disableZip=true, disableCvv=true
useStyles: false,
disableZip: true,
disableCvv: false
});
var form = document.getElementById('paymentForm');
form.addEventListener('submit', function(event) {
event.preventDefault();
tokenpay.createToken(function(result) {
alert(result.token)
}, function(result) {
console.log("error: " + result);
});
});
</script>
<script type="text/javascript" src="http://xxx/tokenPay.js"></script>
<form id="paymentForm" action="xxx" method="post" style="margin: 10%;">
<div id="card" style="border: solid 1px lightgray; height: 100px; width: 500px; padding: 20px 10px; border-radius: 10px; margin: 10px 0px;">
</div>
<div id="errorMessage" style="margin-bottom: 10px; color: #c0392b;"></div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
when I'm using these three-part together on the index page is working fine when I'm trying to work from a component template that is not

Put the script tag <script type="text/javascript" src="http://xxx/tokenPay.js"></script> inside the head tag within index.html
Then put the var tokenpay = TokenPay('tokenpay123'); etc block inside ngAfterViewInit within the relevant component (i.e. the component hosting the form). Then it should work fine.
Note that because tokenPay is a global variable, the TypeScript compiler will not recognise it so you will need to add:
declare const tokenPay: any
inside the .ts file of the relevant component.

It's not clear on what problem you're facing, but I think you have to call the <script type="text/javascript" src="http://xxx/tokenPay.js"></script> after your form. By doing so early, the form may not exist yet

Related

jQuery Event listeners sticking/cascading?

On my web app, I have a screen that expects a user to use a bar-code scanner to scan an item number in, but in the event they do not have one (or the code won't scan) they can click on the notification that asks them to scan and it changes to a box allowing them to enter the details to search manually.
The issue is, the event listener seems to get applied to the close button, it gets removed from the div but the close button seems to call the "open search box" function instead of the "close search box" function
I tried using the jQuery $('#id').one('click' function(){myFunctionHere();}); function to add an event listener on click of the DIV and also tried using $('#id').on('click' function(){myFunctionHere();}); and $('#id').off('click'); but I have the same issue.
See the jsfiddle
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<style>
#tnt-searchScan{
width: 300px;
height: 100px;
border: 5px dashed red;
text-align: center;
}
</style>
<script>
$(document).ready(function(){
$('#tnt-searchScan').one('click', function(){showSearchBox();});
})
function closeSearchBox(){
var html = '<h4>Scan barcode</h4><h4>or click here to search</h4>';
$('#tnt-searchScan').html(html).one('click', function(){showSearchBox();});
}
function showSearchBox(){
console.log('test');
var html = 'Content of search box<button type="button" id="tnt-closeSearchBox">Close</button>';
$('#tnt-searchScan').html(html);
$('#tnt-closeSearchBox').one('click', function(){closeSearchBox();});
}
</script>
</head>
<body>
<div id="tnt-searchScan"><h4>Scan barcode</h4><h4>or click here to search</h4></div><div id="tnt-mainPage"><div class="loader"></div> </div>
</body>
I expect the box to return back to normal, but it does not, if you check the console, every time you click 'Close' "test" appears, signalling that the show function is called. if i call the "closeSearchBox();" manually it works fine.
You need to make some changes in your js. First of all .one is changed to .on second need to change the close function click event because the search form is added with js to dom so you need to fire click event on it like this $(document).on('click','#tnt-closeSearchBox', function(){ closeSearchBox(); });.
$(document).ready(function(){
$('#tnt-searchScan').on('click', function(){showSearchBox();});
})
function closeSearchBox(){
var html = '<h4>Scan barcode</h4><h4>or click here to search</h4>';
$('#tnt-searchScan').html(html).on('click', function(){showSearchBox();});
}
function showSearchBox(){
//console.log('test');
var html = '<label>Search By: <select id="tnt-searchOption">' +
'<option selected>ID</option>' +
'<option>Legacy ID</option>' +
'</select></label>' +
'<label>Search: <input type="text" id="tnt-searchBox"></label>' +
'<button type="button">Search</button><button type="button" id="tnt-closeSearchBox">Close</button>';
$('#tnt-searchScan').html(html);
}
$(document).on('click','#tnt-closeSearchBox', function(){closeSearchBox();});
#tnt-searchScan{
width: 300px;
height: 100px;
border: 5px dashed red;
text-align: center;
}
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
</head>
<body>
<div id="tnt-searchScan"><h4>Scan barcode</h4><h4>or click here to search</h4></div><div id="tnt-mainPage"><div class="loader"></div> </div>
</body>

Printing global variables in body in Javascript

I'm working with a piece of code I'm designing in my free time, which is a bit unorthodox so bear with me here. The page is set to run a variety of pages based on which "" tag the html is being read from. I was just looking for a way to condense a number of pages into a single one, and this seemed like it might be interesting to mess with. If you guys know of better ways to do that, any information would be appreciated.
So far I'd managed to get everything working until I hit a part where I was trying to obtain a form value, assign it to a global variable, and then use a script to print the global variable in the text. In this case, it is asking the user's name, the goal being to reproduce the name in various places throughout the website for a more user-friendly feel. I figure understanding this will be useful in the future. Eventually I'll want to figure out how to create a database of usernames and passwords and all that good stuff, but for now, I'm just looking for a simple fix. I'm probably missing something elementary. Here's the code:
<head>
<style>
body {
margin: 0 auto;
background-image: URL('http://fc04.deviantart.net/fs9/i/2006/033/2/c/Matrix_code_by_phi_AU.jpg');
background-attachment: fixed;
background-repeat: repeat-y;
}
</style>
<meta charset="utf-8">
<title>MasterCode</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
var name = "";
//user is "finished typing," collect input
function doneTyping() {
name = document.getElementById('nameid').value;
closeElement('welcomepage');
closeElement('namepage');
showElement('homepage');
}
function closeElement(myelement) {
document.getElementById(myelement).style.display = "none";
}
function showElement(myelement) {
document.getElementById(myelement).style.display = 'block';
}
function enterWebsite() {
closeElement('namepage');
closeElement('homepage');
$("#dialog").dialog({
autoOpen: false
}, {
title: "Change"
}, {
resizable: false
});
$("#opener").click(function () {
$("#dialog").dialog("open");
closeElement('welcomepage');
showElement('namepage');
})
}
function writeName() {
document.write(name);
}
</script>
</head>
<body onload="enterWebsite()">
<div id="welcomepage">
<button id="opener" style='background: url("http://4.bp.blogspot.com/-fDgJmT5rzlM/Tq8SpW3ZcbI/AAAAAAAAA1I/l02iiclqKkA/s1600/tracking%2Bclub%2Bmeet%2B%2526%2BMisty%2BAlgonquin%2Bshots%2B106.jpg") no-repeat top left; color: #FFFFFF; height: 685px; width: 1350px; font: 75px helvetica, cursive'>Enter MasterCode</button>
</div>
<div id="namepage">
<form id='name_input'>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<center>
<input style="background-image:URL('https://waypointprod.blob.core.windows.net/blogfilestore/storage/blogs/headlines/2013/12/5/image.jpg');background-repeat:no-repeat;background-position: ; border: 50px solid black ; height:50px; width:350px; color: #FFFFFF; font: 45px helvetica, cursive;"
id='nameid' type="text" value="Enter your name.">
<br/>
<button id='submit_name' onclick='doneTyping(); return false;'>I Accept The Risks</button>
</form>
</div>
<div id="homepage">
<font size="25" color="white">
Welcome, <script> writeName(); </script>
</font>
</div>
</body>
</html>
Thoughts?
(Edit: Resolved using localStorage as suggested by tewathia)
Not sure if you're using any sort of RESTful API or even nodejs.
If you are, something I do to prevent storing this data in cookie or in sessionStorage is that I utilize server-side to store. Then you wouldn't need to add as much logic on client-side. This user data could be
{
"name": "Don Jon",
"favorite_color": "blue"
}
you could even display different parts of the page in blue to be super user friendly

.addClass() not working in JQuery function

I have numerous websites that are on a "dev" site meaning that it is dummy data and not all functionality works. What happens is that I have this function in my document.ready() that is supposed to find the html for the popup box and add a class to it, which gives the popup box a little blue header bar.
Function:
$("document").ready(
function(){
//loadSummary();
NOT_AVAILABLE_ALERT = $("#modalMessageAlert").dialog(
{
position: "center",
resizable: false,
bgiframe: true,
autoOpen: false,
width: 250,
height: 200,
draggable: false,
modal: true,
close:function(event,ui){
},
open:function(event,ui){
}
});
modifyModalHeader("modalMessageAlert","demo_dialog_header");
}
);
function modifyModalHeader(id,className){
var refs = $("#"+id).prev();
var ref = refs.eq(0);
ref.addClass(className);
}
function navigateDemo() {
NOT_AVAILABLE_ALERT.dialog("open");
}
HTML
<div id="tempXML" ></div>
<div id="modalMessageAlert"style="left:-200px; display:none">
<h3>This feature is not available in this demo household.</h3>
<input style="margin-bottom: 15px" type="button" Value="Close" onclick="NOT_AVAILABLE_ALERT.dialog('close');"/>
</div>
HTML link:
<input type="submit" onclick="javascript:navigateDemo();return false;" value="Save" id="save"/>
CSS
#modalMessageAlert {
background-color:#fff;
cursor:pointer;
padding: 10px 10px 10px 10px;
text-align:center;
vertical-align:middle;
}
.demo_dialog_header {
background-image:url(/backoffice/Prospects/APP360/images/demo_modal_header.gif)
}
If i understand correctly the modifyModalHeader function is supposed to find the tempXML div using the .prev() functionality and add that class to the tempXML div, and then when a user clicks the "submit" aka save button it shows the dialog, the dialog shows fine, just without the referenced image as the background-image, which just creates a solid blue line across the top about 15px wide. This EXACT same functionality and references work on pages included in the same directories just fine, but for some reason i can't get this to load correctly.
Any help is greatly appreciated.
-NickG
Turns out that i had conflicting style sheets that were overriding the class because i used some JQuery calendar extenders and they were being referenced as ui-widgets as does that popup.

jScrollpane with dynamically loaded content, not scrolling

Alright, so I'm working on a website and currently I have a "shoutbox" at the index page however I'm loading the shouts from another .php file the problem is that the scrollbars shows up but I can't actually scroll, at the moment there are 6 shouts in the DB that are being loaded but I can only see 4 and I can't scroll down any more.
If you want to check out the problem for yourself here is the link to the site (work in progress) http://ecazs.net/beerandguns/index.php
You are only able to see 4 but I can assure you there are 6!
This is the code I use to load shouts.
$(document).ready(function(){
$('.messages').fadeIn("slow").load('shoutbox/load.shouts.php');
setInterval(function() {
$(".messages").load("shoutbox/load.shouts.php");
}, 2000);
});
And this is the "main" HTML of the shoutbox
<div id="chat" class="jspScrollable">
<div class="jspContainer" style="width: 620px; height: 327px;">
<div class="jspPane" style="padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; width: 600px; top: 0px; ">
<form action="" method="post" class="shout">
<p>
<label for="message" class="msglabel">Message:</label>
</p>
<p>
<textarea name="message" id="message" class="msgfield" rows="2" cols="95"></textarea>
</p>
<p>
<input type="image" name="submit" src="ext/images/submit_btn.png" value="" class="submit" onmouseover="this.src = 'ext/images/submit_btn_hover.png';" onmouseout="this.src = 'ext/images/submit_btn.png';"/>
</p>
</form>
<div class="messages"></div>
</div>
I'm then using the jScrollpane function before body ENDS. So I'm first loading the content then the jScrollpane.
$(function(){
$('#chat').jScrollPane();
});
I really need help with this, if you have any ideas on how to solve this or improve it then please, please let me know.
Your HTML is not good for jScrollPane.
You have two .jspContainer and .jspPane in #chat.
Just remove the classes jspContainer and jspPane for the elements in the first div.jspPane
And you have to use the callback function for load, to tell the jScrollPane the content changed.
your js should be something like :
//caching element
var messages = $('.messages'), chat = $('#chat');
messages.fadeIn("slow");
var loadChatContent = function() {
messages.load('shoutbox/load.shouts.php', chat.jScrollPane);
}
loadChatContent();
setInterval(loadChatContent, 2000);
--- update
I's a JS replacement for the one you show us :
$(document).ready(function() {
//caching element
var messages = $('.messages'), chat = $('#chat');
messages.fadeIn("slow");
var loadChatContent = function() {
messages.load('shoutbox/load.shouts.php', chat.jScrollPane);
}
loadChatContent();
setInterval(loadChatContent, 2000);
});
In your website ( not the code you shown ) your html contains two div.jspContainer and two div.jspPane, it will not work if you don't remove class from the elements in you first div.jspPane
Your code :
<div style="width: 640px; height: 327px;" class="jspContainer">
<div style="padding: 5px 10px; width: 600px; top: 0px;" class="jspPane">
<div class="jspContainer" style="width: 620px; height: 327px;">
<div class="jspPane" style="padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; width: 600px; top: 0px; ">
</div>
</div>
<div class="jspVerticalBar">
<div class="jspCap jspCapTop"></div>
<div style="height: 327px;" class="jspTrack">
<div style="height: 318px;" class="jspDrag">
<div class="jspDragTop"></div>
<div class="jspDragBottom"></div>
</div>
</div>
<div class="jspCap jspCapBottom"></div>
</div>
</div>
</div>
jScrollPane will accord the scroll with the height of the content of the first div.jspPane, but in your div.jspPane, you have a second div.jspContainer which have 327px for height. So jScrollPane consider that there is no more content to show. Just remove classes jspContainer and jspPane on line corresponding to my lines 3 and 4, and modify your js, i think it can work like that.
Well, you cannot ensure the jScrollPane() is called after the content has actually loaded by simply placing the code at the end of the page. Both codes are placed in the a DOMready event handler so they are in the end both executed right away as soon as the dom is loaded. I bet the execution plan is:
initiate fist load in .messages
execute jScrollPane
load finishes
And I guess the jScrollPane plugin does not initialize correctly because the content is empty. I don't know much about the plugin itself but I suppose you'd have to refresh it anyway if the content changes to update the scrollbars.
Using the callback of the .load() function will ensure you initialize the jScrollPane when the content has actually loaded:
$(".messages").load("shoutbox/load.shouts.php", function() {
$('#chat').jScrollPane();
});

how do i submit data from HTML using jquery

The question might not be clear, so i will explain further.
I saw some page like wordpress new post tag, they have something like
[input]
x tag | x tag | x tag
or Facebook Notes when you post a image...
the when you input a tag and press enter, a new tag is insert in to element in the page...
I don't quite understand how can you parse that out and then submit to the form.
if anyone know please give me an idea.
Thanks
If I am getting it right, you are talking about sending AJAX-based post requests "under the hood" and get "dynamic reflections" back on the same page.
Well, if this is the case, there are actually more than just submitting data to the server.
Here is the big picture:
You need a javascript which is loaded in the page that has the form to submit.
Inside that script, you need to define the event which will trigger the AJAX-based post request. Basically you would love trigger such an event when the content in that particular field has been just changed (an onChange event, that is).
Then you can use script like the following:
$.ajax
({
type: 'POST',
cache: false,
async: false,
timeout: 10000,
url : '/path/to/your/serverside/function',
dataType : 'json',
data:
{
'tag' : //whatever you want to be used as the tag
},
success : function(message)
{
//this will be called when this post was successfully been carried out.
//you should update the view (the same page) here using some jQuery script.
//such as : $('#tag').html(message.tag);
},
error : function(message)
{
//this is for displaying error messages (perhaps due to networking problems?)
}
});
Since there are really a lot to write about. I suggest you post whatever you have finished up here so we can give it a check.
At least from my consideration, this scenario require the following knowledge to get everything right(though you can always choose to use less tech):
onChange event triggered
|
|
jQuery =====sending JSON formatted tag info ======> serverside function
|
|
decode JSON tag info
|
|
process(saving it into database?)
|
|
encode feedback info
|
jQuery callback function <===== JSON info==================
|
|
update the view(the same page)
.
.
.
.
.
aforementioned process is before form is submitted via normal POST/GET.
One way is to keep track of the tags you add in a hidden form field, but actually display using divs or spans or whatever UI you want. In the case of facebook, I'd imagine they're doing something somewhat similar, though I guess they could actually be adding form elements dynamically. Forgive the nasty code/css - just tossed it together. If you add tags and then hit submit, you'll see the querystring that all the values are there.
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#btnSuggest").click(function(){
var $tagSuggest = $("#tagSuggest");
if($tagSuggest.val() != "")
AddTag($tagSuggest.val());
});
$("#tagSuggest").keyup(function(e){
if(e.keyCode == 13 && $(this).val() != "")
AddTag($(this).val());
});
});
function AddTag(tag){
$("<div>").text(tag).appendTo("#tags").click(function(){
$(this).remove();
UpdateTags();
}).hover(function(){
$(this).addClass("over");
},function(){
$(this).removeClass("over");
});
UpdateTags();
}
function UpdateTags(){
var allTags = "";
$("#tags div").each(function(){
allTags += "," + $(this).text();
});
$("#hidTags").val(allTags.substring(1));
$("#tagSuggest").val("");
}
</script>
<style type="text/css">
.main
{
width: 400px;
padding: 10px;
margin: auto;
border: 1px solid black;
background-color: #e6e6e6;
height: 600px;
}
#tags div
{
padding: 3px;
border: 1px solid black;
background-color: #e6e6e6;
margin: 3px;
height: 15px;
width: auto;
float: left;
cursor: pointer;
}
#tags div.over
{
background-color: red;
}
</style>
</head>
<body>
<div class="main">
<form action="" method="get">
<input type="hidden" name="hidTags" id="hidTags">
<textarea name="Wallpost" style="width: 390px; height: 100px;"></textarea>
<br />
<input type="text" id="tagSuggest" style="width: 280px;" />
<input type="button" id="btnSuggest" value="Add Tag" style="float: right;"/>
<br />
<input type="Submit" name="cmdSubmit" value="Share" style="float: right;"/>
</form>
<div id="tags">
</div>
</div>
</body>
</html>

Categories

Resources