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>
Related
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
I'm trying to get a string of script to run in an href so the link will redirect users depending on an if/else statement. My code:
<div id="editredirect">
<script>
if("[#authfield:Authentications_2_Region]" == "[#field:Location_2_Region_ID]"){
window.location.href = "member-details-edit?CID=[#field:Member_Caspio_ID]&Location_ID=[#field:Member_Location_ID]";
}
else if ("[#authfield:Authentications_2_Region]") == "[#field:Location_2_B_Region_ID]"{
window.location.href = "member-details-edit?CID=[#field:Member_Caspio_ID]&Location_ID=[#field:Member_Location_ID]";
}
else {
window.location.href = "member-details?CID=[#field:Member_Caspio_ID]&Location_ID=[#field:Member_Location_ID]";
}
</script>
</div>
<style type="text/css">a.ex1:hover {color: #f18c21; text-decoration: underline;}
</style>
<a class="ex1" href="javascript:.initialize(document.getElementById("editredirect"));">Details</a>
I've tred do also do a function like this:
<script>
function editredirect {
if("[#authfield:Authentications_2_Region]" == "[#field:Location_2_Region_ID]"){
window.location.href = "member-details-edit?CID=[#field:Member_Caspio_ID]&Location_ID=[#field:Member_Location_ID]";
}
else if ("[#authfield:Authentications_2_Region]") == "[#field:Location_2_B_Region_ID]"{
window.location.href = "member-details-edit?CID=[#field:Member_Caspio_ID]&Location_ID=[#field:Member_Location_ID]";
}
else {
window.location.href = "member-details?CID=[#field:Member_Caspio_ID]&Location_ID=[#field:Member_Location_ID]";
}
}
</script>
<style type="text/css">a.ex1:hover {color: #f18c21; text-decoration: underline;}
</style>
<a class="ex1" href="javascript:editredirect">Details</a>
Neither one will work. The first string returns a syntax error, the second tells me that "editredirect" is undefined.
Thank you!
EDIT
Praveen Kumar's suggestions were the best. The developer for the database I am using was able to get the application to do it without having to insert any script. However, they did say that the event listener would have also worked once I had my parameters correct.
You can use onclick and add the whole JavaScript logic:
Click me?
The best way is to use event listener like this:
document.getElementsByTagName("a")[0].addEventListener("click", function () {
a = prompt('What\'s your name?');
if (a !== null)
alert('Welcome, ' + a);
else
alert('Bye Bye!');
return false;
}, false);
Click me?
This is better than using href. If you still want to run it in href, you need to create a function and run:
function aha() {
a = prompt('What\'s your name?');
if (a !== null)
alert('Welcome, ' + a);
else
alert('Bye Bye!');
return false;
}
Click me?
Note: In your code, you have used wrong notation. That's a syntax error. JavaScript functions have to be declared in a specific way. Follow that!
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?
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.
Hey guys, I have some code that I found that I would rather use as jQuery instead of direct JavaScript. Hopefully you guys can help me convert it:
var sub = document.getElementById('submit');
sub.parentNode.removeChild(sub);
document.getElementById('btn-area').appendChild(sub);
document.getElementById('submit').tabIndex = 6;
if ( typeof _some_var != 'undefined') {
document.getElementById('some-textarea').value = _some_var;
}
document.getElementById('something').style.direction = 'ltr';
The reason I want to do this is because FireFox is telling me that sub is null when it is used on the second line. This happens because that code runs before the the submit button appears. So naturally I would like to use jQuery for the purpose of running the code after everything is ready. Yes, I know it's possible to do that in direct JavaScript as well, but I would rather have jQuery either way.
Thanks!
There's absolutely no need to use jQuery for this purpose. Assuming you do not already have a load event handler:
window.onload = function() {
// your code
};
Or throw it right before the end body tag, or to be more specific anywhere in the source after the submit button - there's nothing really dirty about it.
<script src="your-code.js"></script>
</body>
However, a quick jQuery rewrite..
$(function() {
$('#submit').appendTo('#btn-area').attr('tabIndex', 6);
if ( typeof yourVar != 'undefined' ) {
$('#textarea').val( yourVar );
}
$('#something').css('direction', 'ltr');
});
Did not test.
Here it is:
var sub_html = $('#submit').html();
$('#submit').html('');
$('#btn-area').html(sub_html);
$('#submit').attr('tabindex', 6);
if(typeof _some_var != 'undefined')
{
$('#some-textarea').val(_some_var);
}
$('#something').css('direction', 'ltr');