ReferenceError: functionxyz is not defined - javascript

I am having an error that kinda makes me upset atm. I have three script files, one jQuery, another one including all my functions and the last one is a file where I use one of the function in the functions-script-file.
<!-- SCRIPTS -->
<script type="text/javascript" src="http://localhost/assets/web/js/jquery/de.jq.311.js"></script>
<script type="text/javascript" src="http://localhost/assets/web/js/func.js"></script>
<script type="text/javascript" src="http://localhost/assets/web/js/sign/signup.js"></script>
Signup.js now tells me that a certain function that actually is defined in func.js is not defined, even tho they are all in the correct order and I have checked it twice, the function is spelled the right way. I also have tried to put the functions directly in the head tag above the signup.js and that worked just fine.
func.js:
$(document).ready(function(){
// VARS
var body = $('body');
// FUNCTIONS
var dialerTimeout;
function showDialer(text) {
var t = text;
clearTimeout(dialerTimeout);
var rd = $('response-dialer');
rd.find('.inr p').html(text);
rd.css('bottom', '12px');
dialerTimeout = setTimeout(function(){ rd.removeAttr('style'); }, 3000);
}
});
signup.js:
$(document).ready(function(){
$(document).on('click', '[data-action="signup"]', function(){
var mail = $('input[name="mail"]').val();
var pass = $('input[name="password"]').val();
var pass2 = $('input[name="password2"]').val();
var agb = $('input[name="agb"]').val();
var rd = $('response-dialer');
var lc = $('login-container');
console.log($('[data-form="signup"]').serialize());
if(mail === '' || pass === '' || pass2 === '') {
showDialer('Bitte fülle alle Felder aus!');
} else if(pass !== pass2) {
showDialer('Ihre Passwörter stimmen nicht überein!');
} else if(grecaptcha && grecaptcha.getResponse().length === 0) {
showDialer('Der Captcha-Code ist falsch!');
} else if(!($('#agb').is(":checked"))) {
showDialer('Bitte lese und akzeptiere unsere AGB!');
} else {
if(!validateEmail(mail)) {
showDialer('Ihre E-Mail hat ein falsches Format. Bitte nutze name#host.endung');
} else {
addOverlay(lc);
}
}
});
});

You are getting the error because showDialer is only in the scope of the callback passed to $(document).ready in funcs.js. In order to use it in another script, you have to either define it as a global function, or (better) combine your 2 scripts into one file with just the one $(document).ready enclosing everything.

The issue is your scope. You're defining the functionxyz within the $(document).ready() scope within the first file, which means it's unavailable to the second file, even though their "scope" is the same (document.ready).
You need to define the function you want outside of the document.ready scope so that it can be globally accessed by the signup.js file.

That's because you are wrapping each one of them in a separated $(document).ready function which explains that behavior.
If you don't really need the $(document).ready function for a specific purpose, I would recommend to remove it from both of them and your code will work just fine. But, in case you need it for any reason, just wrap both files together under ONE $(document).ready function so that you can access it without any scoping issue!
For more information about Scope in Javascript, feel free to check this Scope Guide from Scotch.io

Related

The function should be callable

I have two js files. In the first I use this code:
var rightsRef = db.collection("users").doc(uid).collection("rights");
if(createDocumentWithoutId(rightsRef, "readGrades", "false", null, null, null, null) === true) {
window.location.href = "../public/main/main_index.html";
}
else {
}
In the second js file, I use this code:
function createDocumentWithoutId(var databaseRef, var titleValue1, var contentValue1, var titleValue2, var contentValue2, var titleValue3, var contentValue3) {
databaseRef.set({
titleValue1: contentValue1,
titleValue2: contentValue2,
titleValue3: contentValue3,
}).then(function() {
return true;
}).catch(function(error) {
console.error("Error adding document: ", error);
return false;
});
}
That I can call the function of the second js file I "import" both of them in the HTML file, by this way:
<script type="text/javascript" src="javascript1.js"></script>
<script type="text/javascript" src="../javascript2_folder/javascript2.js"></script>
But I am getting this Error:
ReferenceError: createDocumentWithoutId is not defined
You first JS file is being fully executed before the second one. That's what's causing your error - the function in the second file hasn't been loaded yet. You could reverse the order that they're define in your HTML so that the function is defined before it's called.
JS files execute when they're loaded, and in this case execution includes defining the functions. Try reversing the load order of your files, or putting some sort of check on the first code, such as this:
function amIDependentOnAnotherFile(){
if (typeof functionInAnotherFile == 'undefined')
return setTimeout(amIDependentOnAnotherFile, 5);
doSomething();
}

how to open link in external window with click on anchor tag with javascript?

This is probably such a noob question, but I can't get it to work.
I want to open external window link by clicking on anchor tag, but I keep getting error that myFunction() is not defined.
Open link
js
$(document).ready(function() {
$('#searchEng').click(function() {
const engine = document.getElementById('engine');
var en_ = engine.val();
if (en_ == "firefox")
{
function myFunction() {
var url = "https://www.mozilla.org/en-US/firefox/new/";
window.open(url,'_blank');
};
}
});
));
Why is it undefined?
I have .js included because other stuff works.
you can remove function inside click function
$(document).ready(function(){
$('#searchEng').click(function() {
const engine = document.getElementById('engine');
var en_ = engine.val();
if (en_ == "firefox")
{
var url = "https://www.mozilla.org/en-US/firefox/new/";
window.open(url,'_blank');
}
});
Open link
You declared myFunction inside another function, which makes it a local variable of that function. Local variables aren't available outside the function where they were defined.

uncaught reference error jquery is not defined

I'm getting this error:
uncaught reference error jquery is not defined
I receive the error when doing inspect element in Google Chrome.
I don't understand JavaScript and this was done by someone else.
Please note:
I clearly didn't know anything about JS before and the community, although very brutally, made that clear. Sorry about the simplistic post but that wasn't my intention.
This is the script:
function showwaitpagedummy() {
var strSelectedRegion = $('country')[$('country').selectedIndex].text;
var strSelectedDes = $('destair')[$('destair').selectedIndex].text;
var strSelectedFromDes = $('depair')[$('depair').selectedIndex].text;
var strSelectedNights = $('nights')[$('nights').selectedIndex].text;
if (strSelectedRegion == 'Any Region') {
$("dvError").update("You must choose a region");
return false;
} else if (strSelectedDes == 'Any Destination') {
$("dvError").update("You must choose a destination");
return false;
} else if (strSelectedFromDes == 'Any Airport') {
$("dvError").update("You must choose a depature airport");
return false;
} else if (strSelectedNights == 'Any night') {
$("dvError").update("You must choose nights");
return false;
}
$('frmFlightAccom').submit();
$('waitpagedummy').show();
}
You should add a reference to jQuery in your html.
Add this:
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
You should also include
jQuery.noConflict();
Since you use prototype which uses the $. All jQuery code must start with jQuery instead of $.
included jQuery in head & clear cache its working grt
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

javascript revealing module pattern and jquery

I'm trying to up my js foo and start to use the module patter more but I'm struggling.
I have a main page with a jquery-ui element that pops up a dialog that loads an ajax requested page for data entry. The below code is contained within the popup ajax page.
After the pop up is loaded the Chrome console is able to see and execute ProtoSCRD.testing() just fine. If I try to run that in the jQuery.ready block on the page, I get:
Uncaught ReferenceError: ProtoSCRD is not defined
Yet i can execute toggleTypeVisable() in the ready block and life is good. Can anyone shed some light?
$(document).ready(function() {
setHoodStyleState();
$('#hood-style').change(function(){
hstyle = $('#hood-style').val();
if ( hstyle.indexOf('Custom') != -1) {
alert('Custom hood style requires an upload drawing for clarity.');
}
setHoodStyleState();
});
setCapsState();
$('#caps').change(function(){
setCapsState();
});
setCustomReturnVisibility();
$('#return').change(function(){ setCustomReturnVisibility(); });
toggleTypeVisable();
$('#rd_type').change(function(){
toggleTypeVisable();
});
ProtoSCRD.testing();
});
function toggleTypeVisable(){
if ( $('#rd_type').val() == 'Bracket' ) {
$('.endcap-ctl').hide();
$('.bracket-ctl').show();
}
if ( $('#rd_type').val() == 'Endcap' ) {
$('.bracket-ctl').hide();
$('.endcap-ctl').show();
}
if ( $('#rd_type').val() == 'Select One' ) {
$('.bracket-ctl').hide();
$('.endcap-ctl').hide();
}
}
ProtoSCRD = (function($, w, undefined) {
testing = function(){
alert('testing');
return '';
}
getDom = function(){
return $('#prd-order-lines-cnt');
}
return {
testing: testing,
getDom: getDom
};
}(jQuery, window));
calling the popup dialog like so - which is in fact in another ready in a diff file on the parent page:
// enable prototype button
$( "#proto-btn" ).click(function(e){
e.preventDefault();
showPrototype();
});
I don't know if it will solve your problems at all, but you are definitely missing several var statements you really should have:
var ProtoSCRD = (function($, w, undefined) {
var testing = function(){
alert('testing');
return '';
};
var getDom = function(){
return $('#prd-order-lines-cnt');
};
return {
testing: testing,
getDom: getDom
};
}(jQuery, window));
IMHO, it's best practice to use var for every variable you declare. (Function declarations do so implicitly.)
But I really don't know if this will help solve anything. But it should store everything in its proper scope.
Update
Here's one possible issue: if the document is already ready (say this is loading at the end of the body), then perhaps jQuery is running this synchronously. Have you tried moving the definition of ProtoSCRD above the document.ready block?

GetElementById of ASP.NET Control keeps returning 'null'

I'm desperate having spent well over an hour trying to troubleshoot this. I am trying to access a node in the DOM which is created from an ASP.NET control. I'm using exactly the same id and I can see that they match up when looking at the HTML source code after the page has rendered. Here's my [MODIFIED according to suggestions, but still not working] code:
ASP.NET Header
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript">
$(document).ready(
var el = document.getElementById('<%= txtBox.ClientID %>');
el.onchange = alert('test!!');
)
</script>
</asp:Content>
ASP.NET Body
<asp:TextBox ID="txtBox" runat="server"></asp:TextBox>
Resulting Javascript & HTML from above
<script type="text/javascript">
$(document).ready(
var el = document.getElementById('MainContent_txtBox');
el.onchange = alert('test!!');
)
</script>
...
<textarea name="ctl00$MainContent$txtBox" id="MainContent_txtBox"></textarea>
I can only assume that the script is loading before the control id has been resolved, yet when I look at the timeline with Chrome's "Inspect Element" feature, it appears that is not the case. When I created a regular textarea box to test and implement the identical code (different id of course), the alert box fires.
What on earth am I missing here? This is driving me crazy >.<
EDIT: Wierd code that works, but only on the initial page load; firing onload rather than onchange. Even jQuery says that .ready doesn't work properly apparently. Ugh!!
$(document).ready(function() {
document.getElementById('<%= txtBox.ClientID %>').onchange = alert('WORKING!');
})
Assuming the rendered markup does appear in that order, the problem is that the element doesn't yet exist at the time your JavaScript is attempting to locate it.
Either move that JS below the element (preferably right at the end of the body) or wrap it in something like jQuery's document ready event handler.
Update:
In response to your edits, you're almost there but (as others have mentioned) you need to assign a function to the onchange event, not the return result of alert(). Something like this:
$(document).ready(function() {
// Might as well use jQuery to attach the event since you're already using
// it for the document ready event.
$('#<%= txtBox.ClientID %>').change(function() {
alert('Working!');
});
});
By writing onchange = alert('Working');, you were asking JavaScript to assign the result of the alert() method to the onchange property. That's why it was executing it immediately on page load, but never actually in response to the onchange event (because you hadn't assigned that a function to run onchange).
Pick up jQuery.
Then you can
$(function()
{
var el = document.getElementById('<%= txtBox.ClientID %>');
el.onclick() { alert('test!!'); }
});
Other answers have pointed out the error (attempting to access DOM nodes before they are in the document), I'll just point out alternative solutions.
Simple method
Add the script element in the HTML below the closing tag of the element you wish to access. In its easiest form, put it just before the closing body tag. This strategy can also make the page appear faster as the browser doesn't pause loading HTML for script. Overall load time is the same however, scripts still have to be loaded an executed, it's just that this order makes it seem faseter to the user.
Use window.onload or <body onload="..." ...>
This method is supported by every browser, but it fires after all content is loaded so the page may appear inactive for a short time (or perhaps a long time if loading is dealyed). It is very robust though.
Use a DOM ready function
Others have suggested jQuery, but you may not want 4,000 lines and 90kb of code just for a DOM ready function. jQuery's is quite convoluted so hard to remove from the library. David Mark's MyLibrary however is very modular and quite easy to extract just the bits you want. The code quality is also excellent, at least the equal of any other library.
Here is an example of a DOM ready function extracted from MyLibrary:
var API = API || {};
(function(global) {
var doc = (typeof global.document == 'object')? global.document : null;
var attachDocumentReadyListener, bReady, documentReady,
documentReadyListener, readyListeners = [];
var canAddDocumentReadyListener, canAddWindowLoadListener,
canAttachWindowLoadListener;
if (doc) {
canAddDocumentReadyListener = !!doc.addEventListener;
canAddWindowLoadListener = !!global.addEventListener;
canAttachWindowLoadListener = !!global.attachEvent;
bReady = false;
documentReady = function() { return bReady; };
documentReadyListener = function(e) {
if (!bReady) {
bReady = true;
var i = readyListeners.length;
var m = i - 1;
// NOTE: e may be undefined (not always called by event handler)
while (i--) { readyListeners[m - i](e); }
}
};
attachDocumentReadyListener = function(fn, docNode) {
docNode = docNode || global.document;
if (docNode == global.document) {
if (!readyListeners.length) {
if (canAddDocumentReadyListener) {
docNode.addEventListener('DOMContentLoaded',
documentReadyListener, false);
}
if (canAddWindowLoadListener) {
global.addEventListener('load', documentReadyListener, false);
}
else if (canAttachWindowLoadListener) {
global.attachEvent('onload', documentReadyListener);
} else {
var oldOnLoad = global.onload;
global.onload = function(e) {
if (oldOnLoad) {
oldOnLoad(e);
}
documentReadyListener();
};
}
}
readyListeners[readyListeners.length] = fn;
return true;
}
// NOTE: no special handling for other documents
// It might be useful to add additional queues for frames/objects
else {
if (canAddDocumentReadyListener) {
docNode.addEventListener('DOMContentLoaded', fn, false);
return true;
}
return false;
}
};
API.documentReady = documentReady;
API.documentReadyListener = documentReadyListener;
API.attachDocumentReadyListener = attachDocumentReadyListener;
}
}(this));
Using it for your case:
function someFn() {
var el = document.getElementById('MainContent_txtBox');
el.onclick = function() { alert('test!!');
}
API.attachDocumentReadyListener(someFn);
or an anonymous function can be supplied:
API.attachDocumentReadyListener(function(){
var el = document.getElementById('MainContent_txtBox');
el.onclick = function() { alert('test!!');
};
Very simple DOM ready functions can be done in 10 lines of code if you just want one for a specific case, but of course they are less robust and not as reusable.

Categories

Resources