For some reason my javascript code is messed up. When run through firebug, I get the error proceedToSecond not defined, but it is defined!
JavaScript:
<script type = "text/javascript">
function proceedToSecond () {
document.getElementById("div1").style.visibility="hidden";
document.getElementById("div2").style.visibility="visible";
}
function reset_Form() {
document.personalInfo.reset();
}
function showList() {
alert("hey");
if (document.getElementsById("favSports").style.visibility=="hidden") {
document.getElementsById("favSports").style.visibility="visible");
}
}
//function showList2() {
//}
</script>
HTML:
<body>
<!--various code -->
<input type="button" onClick="proceedToSecond()" value="Proceed to second form"/>
</body>
The actual problem is with your
showList function.
There is an extra ')' after 'visible'.
Remove that and it will work fine.
function showList()
{
if (document.getElementById("favSports").style.visibility == "hidden")
{
// document.getElementById("favSports").style.visibility = "visible");
// your code
document.getElementById("favSports").style.visibility = "visible";
// corrected code
}
}
There are a couple of things to check:
In FireBug, see if there are any loading errors that would indicate that your script is badly formatted and the functions do not get registered.
You can also try typing "proceedToSecond" into the FireBug console to see if the function gets defined
One thing you may try is removing the space around the #type attribute to the script tag: it should be <script type="text/javascript"> instead of <script type = "text/javascript">
I just went through the same problem. And found out once you have a syntax or any type of error in you javascript, the whole file don't get loaded so you cannot use any of the other functions at all.
important: in this kind of error you should look for simple mistakes in most cases
besides syntax error, I should say once I had same problem and it was because of bad name I have chosen for function. I have never searched for the reason but I remember that I copied another function and change it to use. I add "1" after the name to changed the function name and I got this error.
Related
I'm looking for a way to pass functions as parameters to the script tag. For example, to make the following work:
<script src="http://path/to/widget.js?param_a=1¶m_b=3" data-myfunc={myfunction()}></script>
<script>
myfunction() {
console.log("hello world")
}
</script>
And then trigger the function from the script.
Since we can pass values in attributes and capture using getAttributes : ref
Try this
<script>
// move function definition above and pass function ref - don't call that function
myfunction(){
console.log("hello world")
}
</script>
<script src="http://path/to/widget.js?param_a=1¶m_b=3" data-myfunc={myfunction}></script>
Yes there is a way!
you can delete the " () "
just turn :
<script src="http://path/to/widget.js?param_a=1¶m_b=3" data-myfunc={myfunction()}></script>
into:
<script src="http://path/to/widget.js?param_a=1¶m_b=3" data-myfunc={myfunction}></script>
And over!
It's my pleasure to help you!
by the way if you are interested, please help me also:
The is my question
that's pretty easy however it won't be accurate as you don't know which script tag will work first or if it will be compiled using inline or not.
if it uses inline your code will not work and you have to use the server to render javascript instead
here is an example using pure javascript. in my understanding you want after loading script /widget.js it will execute function stored in data-myfunc:
widget.js
if (document.currentScript) {
const script = document.currentScript.getAttribute('data-myfunc')
if (script) {
new Function(`
// sandbox faker
const window = undefined;
const document = undefined;
const Document = undefined;
const Window = undefined;
// run script
${script}
`)()
}
} else {
console.warn('widget.js loaded inline. Not working')
}
note if you want to declare the function myFunc after the script /widget.js you have to edit my code to use events like DOMContentLoaded to make sure the function exists
I have the following javascript function that prevents form submission if all required fields are not complete and is part of a form I am creating using Google Apps Scripts. Note that the #submitbutton is actually a regular button and Google Apps Scripts forces strict javascript. The script works fine on chrome, but when I test it on Safari or Firefox, it doesn't appear to be running. Am I using a method that only works on Chrome? Am I missing something here?
I get the following errors in Safari:
Uncaught TypeError: undefined is not a function (evaluating '(1, $)('#submitbutton')') and Uncaught Strict mode does not allow function declarations in a lexically nested statement.
Firefox gives a similar issue: Uncaught in strict mode code, functions may be declared only at top level or immediately within another function 2699307207-maestro_htmlapp_bin_maestro_htmlapp.js:84:360 and Uncaught TypeError: $ is not a function
<script type="text/javascript">
$('#submitbutton').on('click', function() {
$(this).val("Submitting...");
//check for required fields
var emptyFields = $('[required]').filter(function() {
$(this).removeClass("warning");
if ($(this).val().length === 0){
$(this).addClass("warning")
return true
} else {
return false
}
});
if (emptyFields.length === 0) {
$(this).prop('disabled', true);
document.getElementById('incompleteWarning').style.display = 'none';
document.getElementById('bePatient').style.display = 'inline';
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(this.parentNode);
} else{
$(this).val("Submit Application")
document.getElementById('incompleteWarning').style.display = 'inline';
document.getElementById('incompleteWarning').style.color = 'red';
}
});
</script>
jsfiddle here: https://jsfiddle.net/hofresre/
Note that the jsfiddle doesn't use the google.script, but replaces it with this.parentNode.submit()
Any help is greatly appreciated.
Per comments:
Line 84 of maestro_htmlapp_bin_maestro_htmlapp.js:84:360:
function ys(a){for(var b=[],c=0;c<a.length;++c){var d=a[c];b[c]=Mn(d)?(new String(d)).toString():d}return b}var As=[vh,"[object Object]"];var Bs=["alert",ts(function(a){return alert(a)},16,[4]),"confirm",ts(function(a){return confirm(a)},16,[4]),"prompt",ts(function(a,b){return prompt(a,b)},16,[4,4])];var Cs=window.console&&window.console.error?function(a){window.console.error(a)}:void 0,Ds=window.console&&window.console.info?function(a){window.console.info(a)}:void 0,Es=window.console&&window.console.log?function(a){window.console.log(a)}:void 0,Fs=window.console&&window.console.warn?function(a){window.console.warn(a)}:void 0,Gs=["console.debug",ts(window.console&&window.console.debug?function(a){window.console.debug(a)}:void 0,16,[4]),"console.error",ts(Cs,16,[4]),"console.info",ts(Ds,16,[4]),
I guess you know that browser don't support web functionalities the same way. We know that google always focalize their web library and their support firstly for chrome browser.
When you just have this error:
functions can only be declared at top level or immediately within another function
You must not put a function declaration inside any other block, like an if-statement or for-loop; cause any block scope that use curly braces: try-catch-finally, if-else if-else, for, switch, and ES6 also define new feature that utilize block scope such as class.
you can't: "use strict" { Function bar(){/****/} }
Therefore, independents solutions that i can provide are:
Find if there is a version of script (here google script or JQuery) (which is recent) where this problem have been solved.
You can also comment "use strict" in the corresponding script (for example in google script).
Make show that you first include google script and JQuery before the other js scripts.
Try to use non minified script library because something (an example which append with JQuery 1.11) it's the cause of the problem.
Before trying previous solutions, maybe this modified code can work:
<script type="text/javascript">
var trySubmission = function() {
$(this).val("Submitting...");
//check for required fields
var emptyFields = $('[required]').filter(function() {
$(this).removeClass("warning");
if ($(this).val().length === 0){
$(this).addClass("warning")
return true
} else {
return false
}
});
if (emptyFields.length === 0) {
$(this).prop('disabled', true);
document.getElementById('incompleteWarning').style.display = 'none';
document.getElementById('bePatient').style.display = 'inline';
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(this.parentNode);
} else{
$(this).val("Submit Application")
document.getElementById('incompleteWarning').style.display = 'inline';
document.getElementById('incompleteWarning').style.color = 'red';
} ;
}
$('#submitbutton').on('click', trySubmission ) ;
</script>
What mode are you loading the HTML as from the GS file?
When in SandboxMode.NATIVE the error occurs in SandboxMode.IFRAME things seem to work
Here is some test code for a GS file
function doGet(e) {
var html= HtmlService.createTemplateFromFile("test.html");
return html.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
...and the HTML as test.html
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function myFunction() {
if (jQuery) {
// jQuery is loaded
console.log( "Loaded" );
} else {
// jQuery is not loaded
console.log( "Not Loaded" );
}
$("#message").html("Something happened.");
}
$(document).ready(myFunction);
</script>
<p id="message">Nothing happened. </p>
I am creating a function alerts() and call it in my script tag, that is in <head>
Actully currenty i am woking on live editor,so i have to put users code in head,normally all function call in head but here ,it shows error !
I want to hold the user code and run when DOM completes!
like:
HTML
<head>
<script src='alertResource.js' type ='text/javascript' ></script>
<script>
alerts();
<script>
</head>
alertResource.js
function alerts(msg) {
var _M_DoWn = { x: '', y: '', isdown: '' };
var _A = document.createElement('HTML_alert');
_A.id = "codeit_HTML_alert";
insertAfter(document.body, _A);
}
function insertAfter(refrNode, newNode) {
refrNode.parentNode.insertBefore(newNode, refrNode.nextSibling);
}
So, whenever I call the alerts() it shows me an error in my console :
Error
Uncaught TypeError: Cannot read property 'parentNode' of null
I guess the error appears because my function gets called before DOM is loaded. Now I want to do something like: delay any function call until DOM is ready. I know how to check readystate but not able to implement it, as per my case.
Any idea? What I need to do to achieve this?
When you call to "alerts" the document is not fully loaded and "refrNode.parentNode" return null.
Try this, without jQuery
<body onLoad="alerts();">
....
</body>
call your function after page is completely loaded by using this:
Using JavaScriopt
document.addEventListener('DOMContentLoaded', function() {
alerts();
}, false);
Using JQuery
$(function(){
alerts();
});
Please use this. (Javascript way)
window.onload=function(){SomeJavaScriptCode};
<body onload="SomeJavaScriptCode">
Depending on if you need to support IE8 or not, you could do this:
document.addEventListener('DOMContentLoaded', function(){
alerts();
});
I would like to add new attribute to select box which name and id are 'firm_id'. So far I have tried with this code, its working fine in mozila but not working in IE.
I am doing this with javascript because select box is coming from ajax.
The function sbmtfrm() is not calling in IE.
Error: Message: 'FB' is undefined.
May be FB is a object called in my js lib files, but now i am writing code within a another saperate script tag.
<script type="text/javascript">
function sbmtfrm()
{
alert('now submitting...');
document.frmsearch.submit();
}
function setOnclickAtt(name)
{
alert("'"+name+"'" + document.getElementById(name).getAttribute('onchange'));
alert(document.getElementById(name));
if(document.getElementById(name))
{
alert('attrr changed');
var ref = document.getElementById(name);
ref.setAttribute('onchange', 'sbmtfrm();');
alert("now new atrr = " + document.getElementById(name).getAttribute('onchange'));
}
else
{
alert('again');
setTimeout("setOnclickAtt('firm_id')",100);
}
}
setOnclickAtt('firm_id');
</script>
Any suggestion or ideas would be greatly appreciated.
Thanks a lot.
I think IE is picky when it comes to event handling. Try:
ref.onchange = sbmtfrm;
instead of:
ref.setAttribute('onchange', 'sbmtfrm();');
Also, I think the error message has nothing to do with this issue. It´s wrong but it´s another issue.
I'd like to be able to programmatically add a class of console to the <body> tag if Firebug's console.log() was called anywhere on a page. Then I could put some obnoxious message on the screen to remind me not to deploy code with those statements still in it.
The very similar to Eric Meyer's Diagnostic CSS.
Is it possible?
Hehehe. It's an easy mistake to make, isn't it.
Option 1: Always write if(window.console) console.log(...); instead of just console.log(..);
Option 2:
function mydebug(thingtodebug) {
if(window.console) console.log(thingtodebug);
}
..then always use mydebug() instead of console.log();. You could include an else clause that throws up an alert box if console isn't defined.
Option 3:
if(!window.console) {
var console={
log : function() {alert("Don't call console.log");}
}
}
...this will do pretty much exactly what you're asking.
The trouble is that all these options involve including extra code in your live system just to help you avoid embarrassment. (and of course, it'd be even more embarrassing if you miss that alert box!)
If you want to avoid this, a better solution might be to have a separate script that scans your code for any occurrences of console.log. You could run this script as part of your deployment process.
Hope that helps.
This works for me (using jQuery):
$(document).ready(function() {
var body = $('body'),
console = window.console;
console.debug = function() {
if (!body.hasClass('console')) {
body.addClass('console');
console.debug = oldDebug;
}
}
console.debug('foo');
});
It will only add the class the first time our custom function is called. Then it sets console.debug to the original function.
That's the cool thing with javascript, you can override nearly everything :)
It's quite simple. Just override the default console object with your own:
<!DOCTYPE html>
<html>
<head>
<title>Console Test</title>
<script>
var oldConsole = (typeof window.console === "object") ? window.console : null;
var console = {
log: function() {
oldConsole.log(arguments);
document.body.className = "console";
alert('applied class');
}
};
</script>
</head>
<body>
<input type="button" value="click me" onclick="console.log('this is a test');">
</body>
</html>
Live example.