I have a function that receives data from a server and shows a dropzone.js form,
function requestData() {
// showDropzone(); // displaying dropzone from here works,
$.post("/userids/",null, function(data, status) {
jsonarray = JSON.parse(data);
showDropzone(); // here, it calls the function but dropzone is not displayed
});
}
function showDropzone(){
$("#content").html('<form id="dropzone" action="/target" class="dropzone"></form>');
}
Dropzone doesn't show when I call it from inside the post method, but it does when I call it from outside of it. I have no idea what is causing this, there is no error or warning, and I've tried with all possible dropzone configurations, but even forceFallback set to true doesn't work.
EDIT:
Here is the complete html,
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="dropzone.js"></script>
</head>
<body>
<div id="container">
<div id="content"></div>
</div>
<script type="text/javascript">
$(document).ready(function(){
requestData();
});
function requestData() {
// showDropzone(); // displaying dropzone from here works,
$.post("/userids/",null, function(data, status) {
jsonarray = JSON.parse(data);
showDropzone(); // here, it calls the function but dropzone is not displayed
});
}
function showDropzone(){
$("#content").html('<form id="dropzone" action="/target" class="dropzone"></form>');
}
</script>
</body>
</html>
:D I bet form#dropzone adds to the #content, but you don't see it ... because it's EMPTY!! (no input inside) :D Check out my fiddle!
http://jsfiddle.net/U5wCw/
Change your code to
$("#content").html('<form id="dropzone" action="/target" class="dropzone"><input type="text"/></form>');
Related
So, i've been experimenting with de google apps script lately. So far so good, but i ran into a problem that's drivin me out: I have a button in a spreadsheet that calls a sidebar menu with a function in scripts
macros.gs
function sbCases() {
var Form = HtmlService.createTemplateFromFile("Cases");
var ShowForm = Form.evaluate();
ShowForm.setTitle("ASS-CAD - Cases manager system").setHeight(400).setWidth(1000);
SpreadsheetApp.getUi().showSidebar(ShowForm);
the html file I call with this function works just fine, but I'd like to call a second form, also trough an html file to manage the spreadsheet data. So i've added this function to the .gs file (and started a new html file):
function NovoCasoMSE(){
var Form = HtmlService.createTemplateFromFile("NewCase");
var ShowForm = Form.evaluate();
ShowForm.setTitle("New Case").setHeight(400).setWidth(1000);
SpreadsheetApp.getUi().showModalDialog(ShowForm, "New Case");
}
but when I try to call it from a button in the first html file, nothing happens at clicking the button (checked the log and the function the button should call isn't being executed.
Follow the code (the html is full of stuff, like the buttons and everything)("btn" is the ID for a button working on the html file):
<script>
document.getElementById("btn").addEventListener("click", NewCase);
function NewCase(){
google.script.run.NewCase()
}
</script>
I'm learning c in college but have very little experience in javascript ou google script, so I'm pretty sure I've done something really wrong. Thanks for any help in advance. :)
You can try something like this:
Run showTSidebar to get things rolling and then click the button.
ag1.gs:
function loadForm() {
var html='<form><input type="text" name="name1"/><input type="button" value="Click" onClick="process(this.parentNode);" /></form>';
return html;
}
function showTSidebar() {
SpreadsheetApp.getUi().showSidebar(HtmlService.createTemplateFromFile('ah4').evaluate());
}
function processForm(obj) {
SpreadsheetApp.getUi().alert('name1: ' + obj.name1);
}
function include(filename){
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
ah4.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('sbresrc') ?>
</head>
<body>
<div id="form"></div>
<input type="button" value="Load Form" onClick="loadForm();" />
<?!= include('ah6') ?>
</body>
</html>
ah6.html:
<script>
function loadForm() {
google.script.run
.withSuccessHandler(function(html){
$('#form').html(html);
$('#form').css('display','block');
})
.loadForm();
}
function process(obj) {
google.script.run.processForm(obj);
}
</script>
sbresrc.html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
animation:
I'm beginner in Javascript.
I'm learning Browser Object Model.
Then, I had a error message from Chrome console.
My codes are below.
<html>
<head>
<title>
</title>
<meta charset="UTF-8" />
<script type="text/javascript">
function showLinks() {
showLinks_NOT_ERROR1();
showLinks_NOT_ERROR1();
showLinks_WANTED_BUT_ERROR();
}
function showLinks_NOT_ERROR1() {
console.log(document.links[0].href);
console.log(document.links[1].href);
}
function showLinks_NOT_ERROR2() {
alert(document.links[0].href);
alert(document.links[1].href);
}
function showLinks_NOT_ERROR3() {
document.write(document.links[0].href);
}
function showLinks_WANTED_BUT_ERROR() {
document.write(document.links[0].href);
document.write(document.links[1].href);
}
</script>
</head>
<body onload="showLinks();">
google
yahoo
</body>
</html>
As you could see in showLinks_NOT_ERROR3, just one document.write(document.links[0].href); has no error but two document.write(document.links[0].href); document.write(document.links[1].href); has error.
Why does this error happen?
Further to my comment:
When using document.write always note:
'document.write()' is used to write to the document stream.
Calling 'document.write()' on a closed document stream automatically calls document.open(), which will clear the document.
See the correct answer marked in this post:
document.write clears page
<!DOCTYPE html>
<html>
<head><title>Test</title></head>
<body>
google
yahoo
<script type="text/javascript">
function showLinks() {
showLinks_NOT_ERROR1();
showLinks_NOT_ERROR2();
showLinks_WANTED_BUT_ERROR();
}
function showLinks_NOT_ERROR1() {
console.log(document.links[0].href);
console.log(document.links[1].href);
}
function showLinks_NOT_ERROR2() {
alert(document.links[0].href);
alert(document.links[1].href);
}
function showLinks_NOT_ERROR3() {
document.write(document.links[0].href);
}
function showLinks_WANTED_BUT_ERROR() {
document.write(document.links[0].href);
document.write(document.links[1].href);
}
showLinks();
</script>
</body>
</html>
This code should work for you. Here the showLinks function is called before the document stream is closed.
I'm using QUnit for unit testing js and jquery.
My HTML looks like this:
<!DOCTYPE html>
<html>
<head>
<title>QUnit Test Suite</title>
<script src="../lib/jquery.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.16.0.css" type="text/css" media="screen">
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<!--This is where I may have to add startPage.html--->
<script src="../login.js"></script>
<script src="../test/myTests.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
</body>
</html>
Currently, I'm adding login.js as shown and I'm getting references correctly to objects defined in login.js.
However, functions in login.js contains references to some dom elements defined in startPage.html which is located elsewhere.
So, if I say $('#login-btn'), it is throwing an error. Is there any way to fix this?
Can I
(a) refer to startPage.html to my qunit page given above?
(b) refer to or load startPage.html in the file where I'm running tests (myTests.js):
QUnit.test( "a test", function( assert ) {
assert.equal( 1, "1", "String '1' and number 1 have the same value" );//works
assert.equal( login.abc, "abc", "Abc" );//works with attributes
assert.equal(($("#userid").val()),'', 'Userid field is present');//fails
assert.equal( login.ValidUserId(), true, "ValidUserId" );//fails with functions
});
Does QUnit provide any method to load Html/php files so they'll be defined prior to testing. Like 'fixtures' in jasmine?
EDIT: Please also tell what to do in case I have startPage.php
There are a couple of ways you can do this. The simplest is just to use the built-in QUnit "fixtures" element. In your QUnit HTML file, simply add any HTML you want in the div with the id of qunit-fixture. Any HTML you put in there will be reset to what it was on load before each test (automatically).
<html>
...
<body>
<div id='qunit'></div>
<div id='qunit-fixture'>
<!-- everything in here is reset before each test -->
<form>
<input id='userid' type='text'>
<input id='login-btn' type='submit'>
</form>
</div>
</body>
</html>
Note that the HTML in the fixture doesn't really have to match what you have in production, but obviously you can do that. Really, you should just be adding the minimal necessary HTML so that you can minimize any side effects on your tests.
The second option is to actually pull in the HTML from that login page and delay the start of the QUnit tests until the HTML loading is complete:
<html>
<head>
...
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<script>
// tell QUnit you're not ready to start right away...
QUnit.config.autostart = false;
$.ajax({
url: '/path/to/startPage.html',
dataType: 'html',
success: function(html) {
// find specific elements you want...
var elem = $(html).find(...);
$('#qunit-fixture').append(elem);
QUnit.start(); // ...tell QUnit you're ready to go
}
});
</script>
...
</head>
...
</html>
Another way to do this without using jquery is as follows
QUnit.config.autostart = false;
window.onload = function() {
var xhr = new XMLHttpRequest();
if (xhr) {
xhr.onloadend = function () {
if(xhr.status == 200) {
var txt = xhr.responseText;
var start = txt.indexOf('<body>')+6;
var end = txt.indexOf('</body>');;
var body_text = txt.substring(start, end);
var qunit_fixture_body = document.getElementById('qunit-fixture');
qunit_fixture_body.innerHTML = body_text;
}
QUnit.start();
}
xhr.open("GET", "index.html");
xhr.send();
} else {
QUnit.start(); //If getting the html file from server fails run tests and fail anyway
}
}
Special thanks to Raúl Monge for posting a fully working code for me.
My problem was getting JSON data from a file.json and using this data to autocomplete search on it with JavaScript. The code that finaly got it working for me is the following:
<script>
$(document).ready(function(){
var arrayAutocomplete = new Array();
$.getJSON('json/telefoonnummers.json', function(json) {
$.each(json.personen.persoon,function(index, value){
arrayAutocomplete[index] = new Array();
arrayAutocomplete[index]['label'] = value.naam+" - "+value.telefoonnummer;
});
$( "#search" ).autocomplete({source: arrayAutocomplete});
});
});
This is the html:
<body>
<div id="content">
<input type="text" id="search" />
</div>
And this has to be included in the head:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
Thanks stackoverflow!
NEW EDIT CODE WORKING:
<script>
$(document).ready(function(){
var arrayAutocomplete = new Array();
$.getJSON('data.json', function(json) {
$.each(json.persons.person,function(index, value){
arrayAutocomplete[index] = new Array();
arrayAutocomplete[index]['label'] = value.name;
arrayAutocomplete[index]['value'] = value.phoneno;
});
$( "#search" ).autocomplete({source: arrayAutocomplete});
});
});
</script>
Add this in head
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
This is the html
<body>
<div id="content">
<input type="text" id="search" />
</div>
</body>
why not use
var data = [
"Aragorn",
"Arwen",
....
];
since all of those data are labels?
There you go
A working example with the data structure you have.
Just initialize the autocomplete once the JSON is loaded & the data is formatted.
$( "#search" ).autocomplete({source: availableTags});
Your document ready is within your function.
Try to write your function outside of your document ready.
Then write your document ready to call your function.
Some something like this:
function loadJson() {
//alert("Whoohoo, you called the loadJson function!"); //uncomment for testing
var mycontainer = [];
$.getJSON( "data.json" , function(data) {
//alert(data) //uncomment for testing
$.each( data, function( key, val ) {
//alert("key: "+key+" | val: "+val); //uncomment for testing
array.push([key , val]);
});
});
return mycontainer;
}
$(document).ready(function(){
//alert("Boojah! jQuery library loaded!"); //uncomment for testing
var content = loadJson();
dosomethingwitharray(content);
});
Hope this helps!
Also make sure you have jQuery included in your head ( <head> </head> ):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
And add your javascript at the end of your body ( <body> </body> ).
To test if jquery does it's job try this:
<html>
<head>
<title>getting started with jquery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
</head>
<body>
<h1>my page</h1>
<p>this paragraph contains some text.</p>
<!-- javascript at end -->
<script>
$(document).ready(function(){
//show a dialog, confirming when the document is loaded and jquery is used.
alert("boojah, jquery called the document ready function");
//do something with jquery, for example, modify the dom
$("p").append('<br /> i am able to modify the dom with the help of jquery and added this line, i am awesome.');
});
</script>
</body>
</html>
PS. Uncomment alerts for testing stuff, so you can test what happens. If you have space in your document i suggest using $.append to an div that log's all action's so you can see exactly what's going on because alert's in a loop like the .each are quite annoying! more about append: http://api.jquery.com/append/
I have two scripts and I need to use script1 function in script2. Whats the best way to do it and Is there any simplification using prototype to access function in more scripts. I am using jquery.
script1
$(function(){
function process(){
// some code
}
})
script2
$(function(){
// I would like to use the process function here
}
Sample.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<script type="text/javascript" charset="utf-8" src="Script1.js" ></script>
<script type="text/javascript" charset="utf-8" src="Script2.js" ></script>
<script>
</script>
<BODY onload='calling();'>
</BODY>
</HTML>
Scrip1.jc
function call(){
alert("Hi i am called from script2");
}
Scrip2.js
function calling(){
call();
}
Hope this help you.
You can use javascript functions as variables. So just reread your question about the same stuff about variables - Unable to access variable
So just do so your function will be available from global scope.
Just move the function declaration outside the ready event handler, that will make it globally available.
Another idea: use objects:
var Ob = {
process: function(callback) {
callback();
}
}
script1
$(function(){
Ob.process(function(){
... // code
});
});
script 2 (do same)
$(function(){
Ob.process(function(){
... //another code
});
});
If you are using same process function (means same body content, make same thing in both script) then
var Ob = {
process: function() {
...//put code
}
}
script1
$(function(){
Ob.process();
});
script 2 (do same)
$(function(){
Ob.process();
});