[jQuery] Re: Variable Scope Help
Thank you James for the help! I didn't know that the address is static once you've initialized it. I'm trying to work with the extraParams option but it doesn't seem to do anything. Here is how I have it set: //Item Search for food name $(#add-item #ITEMNAME).autocomplete(?= site_url('aloha/ item_search'); ?, { extraParams: categoryID, selectFirst: false, formatItem: formatItem, formatResult: formatResult }).result(function(row, item, data) { $('#add-item #ITEMNAME').val(item[0]); $('#add-item #ITEMID').val(item[1]); }); Just setting it like that doesn't seem to add anything to AJAX call. On Aug 27, 4:11 pm, James james.gp@gmail.com wrote: It's not really a variable scope problem. You're misunderstanding when variables are set. This is what's happening: set global variable categoryID add change event add autocomplete with URL set to aloha/item_search/+categoryID - categoryID is blank do rest of page When you do your change event, you do update the categoryID variable, but not the autocomplete URL. Once that URL is set on initialization, it's set. Changing categoryID is not going to change the autocomplete URL. I'm not sure if there is a way to update the autocomplete URL once it's initialized without having to re-initialize it again. Is it necessary that the URL has to change? Could you not use autocomplete's 'extraParams' option to add additional data to the call?http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_datao... The difference with using extraParams is that the values are calculated at the time of the call, so you'll have dynamic values. On Aug 27, 7:06 am, WhoButSB whobu...@gmail.com wrote: Hello All, I'm running into some issues where I'm alittle confused about the scope of my variables. I have this code: $(function(){ var categoryID; //Aloha Item Category Dropdown Selection //Takes the Selected Value and adds it to Item Search Ending $(#add-item select[name='CategoryId']).change(function(){ categoryID = $(#add-item select[name='CategoryId'] :selected).val (); return categoryID; }); //Item Search for food name $(#add-item #ITEMNAME).autocomplete(?= site_url('aloha/ item_search'); ?/+categoryID, { selectFirst: false, formatItem: formatItem, formatResult: formatResult }).result(function(row, item, data) { $('#add-item #ITEMNAME').val(item[0]); $('#add-item #ITEMID').val(item[1]); }); } What I'm trying to do is take a selection value from a drop down menu and append the value to the end of the URL in the auocomplete plugin. For some reason I'am not able to get this to work. Whenever I view the AJAX request it says that the value is undefined. But if I put a console.log() into where I select the value it comes up correctly. I believe its the way i'm defining the vairables scope. THank you for the help!
[jQuery] Re: Variable Scope Help
I haven't tested this, nor tried it before, but based on the documentation the data type of extraParams has to be an object, or a function (that probably returns an object). function getCategoryID() { return {catID:categoryID}; // 'catID' will be the name of the categoryID in your script // e.g. /?catID=vegetable } //Item Search for food name $(#add-item #ITEMNAME).autocomplete(?= site_url('aloha/ item_search'); ?, { extraParams: getCategoryID, selectFirst: false, formatItem: formatItem, formatResult: formatResult }).result(function(row, item, data) { $('#add-item #ITEMNAME').val(item[0]); $('#add-item #ITEMID').val(item[1]); }); On Aug 27, 10:26 am, WhoButSB whobu...@gmail.com wrote: Thank you James for the help! I didn't know that the address is static once you've initialized it. I'm trying to work with the extraParams option but it doesn't seem to do anything. Here is how I have it set: //Item Search for food name $(#add-item #ITEMNAME).autocomplete(?= site_url('aloha/ item_search'); ?, { extraParams: categoryID, selectFirst: false, formatItem: formatItem, formatResult: formatResult }).result(function(row, item, data) { $('#add-item #ITEMNAME').val(item[0]); $('#add-item #ITEMID').val(item[1]); }); Just setting it like that doesn't seem to add anything to AJAX call. On Aug 27, 4:11 pm, James james.gp@gmail.com wrote: It's not really a variable scope problem. You're misunderstanding when variables are set. This is what's happening: set global variable categoryID add change event add autocomplete with URL set to aloha/item_search/+categoryID - categoryID is blank do rest of page When you do your change event, you do update the categoryID variable, but not the autocomplete URL. Once that URL is set on initialization, it's set. Changing categoryID is not going to change the autocomplete URL. I'm not sure if there is a way to update the autocomplete URL once it's initialized without having to re-initialize it again. Is it necessary that the URL has to change? Could you not use autocomplete's 'extraParams' option to add additional data to the call?http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_datao... The difference with using extraParams is that the values are calculated at the time of the call, so you'll have dynamic values. On Aug 27, 7:06 am, WhoButSB whobu...@gmail.com wrote: Hello All, I'm running into some issues where I'm alittle confused about the scope of my variables. I have this code: $(function(){ var categoryID; //Aloha Item Category Dropdown Selection //Takes the Selected Value and adds it to Item Search Ending $(#add-item select[name='CategoryId']).change(function(){ categoryID = $(#add-item select[name='CategoryId'] :selected).val (); return categoryID; }); //Item Search for food name $(#add-item #ITEMNAME).autocomplete(?= site_url('aloha/ item_search'); ?/+categoryID, { selectFirst: false, formatItem: formatItem, formatResult: formatResult }).result(function(row, item, data) { $('#add-item #ITEMNAME').val(item[0]); $('#add-item #ITEMID').val(item[1]); }); } What I'm trying to do is take a selection value from a drop down menu and append the value to the end of the URL in the auocomplete plugin. For some reason I'am not able to get this to work. Whenever I view the AJAX request it says that the value is undefined. But if I put a console.log() into where I select the value it comes up correctly. I believe its the way i'm defining the vairables scope. THank you for the help!
[jQuery] Re: Variable Scope Help
It's not really a variable scope problem. You're misunderstanding when variables are set. This is what's happening: set global variable categoryID add change event add autocomplete with URL set to aloha/item_search/+categoryID - categoryID is blank do rest of page When you do your change event, you do update the categoryID variable, but not the autocomplete URL. Once that URL is set on initialization, it's set. Changing categoryID is not going to change the autocomplete URL. I'm not sure if there is a way to update the autocomplete URL once it's initialized without having to re-initialize it again. Is it necessary that the URL has to change? Could you not use autocomplete's 'extraParams' option to add additional data to the call? http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions The difference with using extraParams is that the values are calculated at the time of the call, so you'll have dynamic values. On Aug 27, 7:06 am, WhoButSB whobu...@gmail.com wrote: Hello All, I'm running into some issues where I'm alittle confused about the scope of my variables. I have this code: $(function(){ var categoryID; //Aloha Item Category Dropdown Selection //Takes the Selected Value and adds it to Item Search Ending $(#add-item select[name='CategoryId']).change(function(){ categoryID = $(#add-item select[name='CategoryId'] :selected).val (); return categoryID; }); //Item Search for food name $(#add-item #ITEMNAME).autocomplete(?= site_url('aloha/ item_search'); ?/+categoryID, { selectFirst: false, formatItem: formatItem, formatResult: formatResult }).result(function(row, item, data) { $('#add-item #ITEMNAME').val(item[0]); $('#add-item #ITEMID').val(item[1]); }); } What I'm trying to do is take a selection value from a drop down menu and append the value to the end of the URL in the auocomplete plugin. For some reason I'am not able to get this to work. Whenever I view the AJAX request it says that the value is undefined. But if I put a console.log() into where I select the value it comes up correctly. I believe its the way i'm defining the vairables scope. THank you for the help!
[jQuery] Re: Variable Scope Help
Oh, the reason I used a function instead of: extraParams: {catID:categoryID}, is because the function acts as a callback that will execute right before the AJAX call to get the updated data for categoryID, otherwise it will just be the same as the URL, set only on initialization (which is blank). On Aug 27, 11:13 am, James james.gp@gmail.com wrote: I haven't tested this, nor tried it before, but based on the documentation the data type of extraParams has to be an object, or a function (that probably returns an object). function getCategoryID() { return {catID:categoryID}; // 'catID' will be the name of the categoryID in your script // e.g. /?catID=vegetable } //Item Search for food name $(#add-item #ITEMNAME).autocomplete(?= site_url('aloha/ item_search'); ?, { extraParams: getCategoryID, selectFirst: false, formatItem: formatItem, formatResult: formatResult }).result(function(row, item, data) { $('#add-item #ITEMNAME').val(item[0]); $('#add-item #ITEMID').val(item[1]); }); On Aug 27, 10:26 am, WhoButSB whobu...@gmail.com wrote: Thank you James for the help! I didn't know that the address is static once you've initialized it. I'm trying to work with the extraParams option but it doesn't seem to do anything. Here is how I have it set: //Item Search for food name $(#add-item #ITEMNAME).autocomplete(?= site_url('aloha/ item_search'); ?, { extraParams: categoryID, selectFirst: false, formatItem: formatItem, formatResult: formatResult }).result(function(row, item, data) { $('#add-item #ITEMNAME').val(item[0]); $('#add-item #ITEMID').val(item[1]); }); Just setting it like that doesn't seem to add anything to AJAX call. On Aug 27, 4:11 pm, James james.gp@gmail.com wrote: It's not really a variable scope problem. You're misunderstanding when variables are set. This is what's happening: set global variable categoryID add change event add autocomplete with URL set to aloha/item_search/+categoryID - categoryID is blank do rest of page When you do your change event, you do update the categoryID variable, but not the autocomplete URL. Once that URL is set on initialization, it's set. Changing categoryID is not going to change the autocomplete URL. I'm not sure if there is a way to update the autocomplete URL once it's initialized without having to re-initialize it again. Is it necessary that the URL has to change? Could you not use autocomplete's 'extraParams' option to add additional data to the call?http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_datao... The difference with using extraParams is that the values are calculated at the time of the call, so you'll have dynamic values. On Aug 27, 7:06 am, WhoButSB whobu...@gmail.com wrote: Hello All, I'm running into some issues where I'm alittle confused about the scope of my variables. I have this code: $(function(){ var categoryID; //Aloha Item Category Dropdown Selection //Takes the Selected Value and adds it to Item Search Ending $(#add-item select[name='CategoryId']).change(function(){ categoryID = $(#add-item select[name='CategoryId'] :selected).val (); return categoryID; }); //Item Search for food name $(#add-item #ITEMNAME).autocomplete(?= site_url('aloha/ item_search'); ?/+categoryID, { selectFirst: false, formatItem: formatItem, formatResult: formatResult }).result(function(row, item, data) { $('#add-item #ITEMNAME').val(item[0]); $('#add-item #ITEMID').val(item[1]); }); } What I'm trying to do is take a selection value from a drop down menu and append the value to the end of the URL in the auocomplete plugin. For some reason I'am not able to get this to work. Whenever I view the AJAX request it says that the value is undefined. But if I put a console.log() into where I select the value it comes up correctly. I believe its the way i'm defining the vairables scope. THank you for the help!
[jQuery] Re: variable scope
In this line of code: $('.menu_button').click(this.onClick); you are getting a refernece to your onClick function. But that's all you get - a *function* reference. It doesn't remember that you said 'this.onClick' to get that reference. As you found, when that function gets called later by jQuery's click event code, 'this' means something else entirely - it's a reference to the element receiving the event. The classic way of fixing this (pun intended) is to use a closure. You could change that line of code to: var bar = this; $('.menu_button').click( function() { bar.onClick(); }); But food for thought: How many MenuBar instances will you be creating? Just one or a small number? Then you can simplify the code considerably by not using a prototype. Instead, put the methods inside the constructor and use a closure for all your object references: function MenuBar() { var bar = this; bar.currentIndex = 0; $('.menu_button').click(onClick); function onClick(evt) { bar.currentIndex = 1; bar.select(bar.currentIndex); }; bar.select = function(index) { //code goes here }; }; The idea is to get 'this' into a local variable ('bar') right away, and then use 'bar' everywhere that you would have used 'this'. onClick doesn't need to be a method of the object because you would never call it directly, so it's just a nested function. I assume that Select() would be called as an object method and left it as such - but I changed its name to select(). Standard JavaScript practice is to use an initial capital letter in constructors only, and initial lowercase for other functions and methods. I left currentIndex as a property of the object, but if you only need it inside the constructor and object methods, you can do it this way instead: function MenuBar() { var bar = this; var currentIndex = 0; $('.menu_button').click(onClick); function onClick(evt) { currentIndex = 1; bar.select(currentIndex); }; bar.select = function(index) { //code goes here }; }; You can also use an anonymous function for onClick: function MenuBar() { var bar = this; var currentIndex = 0; $('.menu_button').click( function(evt) { currentIndex = 1; bar.select(currentIndex); }); bar.select = function(index) { //code goes here }; }; -Mike From: mrtedweb Hello everyone, I'm new to jQuery and need some help with a trivial question. I'm trying to program a menu bar and I'm having problems with variable scope. Below is a snippet of my code: // ** script type=text/javascript $(document).ready(function() { var menubar = new MenuBar(); }); /script script type=text/javascript function MenuBar() { this.currentIndex = 0; $('.menu_button').click(this.onClick); }; MenuBar.prototype.onClick = function(evt) { this.currentIndex = 1; //--Unable to access class variable!! this.Select(this.currentIndex); //--Unable to access class funtion!! }; MenuBar.prototype.Select = function(index) { //code goes here }; /script // ** Once the onClick event is received the scope move from the class to the actual item itself. How do I access class variables amd functions after receiving an event?? Any help is greatly appreciated. -Ted
[jQuery] Re: Variable scope trouble
Thank you Mike! It works perfect now.
[jQuery] Re: Variable scope trouble
After getting a good nights sleep, and doing more research, it seems the problem is not scope-related, but ajax-related. The advice I have read suggests setting return values from within the ajax callback function, because of the asynchronous completion of the ajax function. So, I have attempted to apply the tooltip functions within the ajax callback, but without success. The ajax is returning it's values, but the tooltip is not being applied. Any advice welcome. Thanks! $('a[href^=logmar]').queue(function(){ var args = $(this).attr(href).split('?')[1]; if(args.charAt(0) == l) { var lm = args.substring(2, args.length); $.get(templates/templates.php, {'action': 'lm2sn', 'l' : lm }, function(response){ if(response.length 0) { $(this).tooltip({ bodyHandler: function() { return response; }, showURL: false }); } }); } });
[jQuery] Re: Variable scope trouble
The problem is the use of 'this' in the inner function. In that code it no longer means what you want it to mean. Try this (pun intended) instead: $('a[href^=logmar]').queue(function(){ var $this = $(this); var args = $this.attr(href).split('?')[1]; if(args.charAt(0) == l) { var lm = args.substring(2, args.length); $.get(templates/templates.php, {'action': 'lm2sn', 'l' : lm }, function(response){ if(response.length 0) { $this.tooltip({ bodyHandler: function() { return response; }, showURL: false }); } }); } }); I don't know if there are any other remaining errors, but that will be one more down. -Mike From: rhodopsin After getting a good nights sleep, and doing more research, it seems the problem is not scope-related, but ajax-related. The advice I have read suggests setting return values from within the ajax callback function, because of the asynchronous completion of the ajax function. So, I have attempted to apply the tooltip functions within the ajax callback, but without success. The ajax is returning it's values, but the tooltip is not being applied. Any advice welcome. Thanks! $('a[href^=logmar]').queue(function(){ var args = $(this).attr(href).split('?')[1]; if(args.charAt(0) == l) { var lm = args.substring(2, args.length); $.get(templates/templates.php, {'action': 'lm2sn', 'l' : lm }, function(response){ if(response.length 0) { $(this).tooltip({ bodyHandler: function() { return response; }, showURL: false }); } }); } });
[jQuery] Re: Variable scope
Hoping someone can help me out with this. I'd appreciate any help.
[jQuery] Re: Variable scope
DanielMedia wrote: This function always returns false. The success variable is not being changed within the getJSON function. I'd appreciate any help. Thanks. var check_user = function() { var success = false; $.getJSON(url, function(response) { if(response.ok) { alert(response.ok); // (evaluates to true) success = true; // The parent success variable doesn't change. } }); return success; } The trouble is that the 'A' in 'AJAX' stands for 'Asynchronous'. The .getJSON call returns immediately, before the anonymous callback completes. You will need to structure somewhat differently if you want to use the results of the AJAX call in this manner. I would suggest passing in a callback function to your check_user function var check_user = function(handler) { $.getJSON(url, function(response) { if (response.ok) { handler(true); } else { handler(false); } } // ... check_user(function(userOk) { alert(User + (userOk ? : not) + ok); // ... whatever you need to do here. }); Good luck, -- Scott
[jQuery] Re: Variable scope
if check_user_auth is a file it doesn't have an extension for url DanielMedia wrote: Hi, I'm pretty new to jQuery. I'm having a problem with variable scope. This function always returns false. The success variable is not being changed within the getJSON function. I'd appreciate any help. Thanks. var check_user = function() { var success = false; url = "" + '/ajax/check_user_auth'; $.getJSON(url, function(response) { if(response.ok) { alert(response.ok); // (evaluates to true) success = true; // The parent "success" variable doesn't change. This function always returns false. } }); return success; }
[jQuery] Re: variable scope bug in Firefox only?
There must be something else going on with your code other than the snippet you've posted here. It's hard to believe that a local variable would not work properly in Firefox. If you could post a link to a complete test page, I'll bet someone could tell you what is going wrong. -Mike From: Liam Morley I'm experiencing an issue in Firefox 3 where, if a variable is declared locally, it doesn't return expected results. I've tried the same thing in IE7 and Chrome, I don't experience the bug in those browsers. My particular example is as follows: var children = $(ul.cat_container li.column:not(.pinned):first); if (children.length 0) { ... } else { ... } In *Firefox only*, children.length will never be greater than 0, unless children is declared globally (without 'var'). Has anyone else run up against this? Is this a Firefox issue, or a jquery issue? (Or potentially a problem with my code? In which case, why would I have different behavior in only one browser...)
[jQuery] Re: Variable scope: Newbie Question
Hi Micheal, Thank you so much for that. I knew I was getting close to a solution but I was well and truly stuck. It is now working and I am delighted. This is the code that worked for me success: function(xml) { towncity = []; $(xml).find([EMAIL PROTECTED]'+ currprov +'] TOWN_CITY_NAME).map (function(){ towncity.push( $(this).text() ); $(#city).autocomplete(towncity); }); } The XML file I am querying is a file I constructed myself (so I have full access to it) for a few different reasons. I am not good enough at mySQL to create a database with the information, I am too cheap to pay for a ready made database ;), the autocomplete script gives an option of storing the data in a local.js file but I did not like this idea as it may not transfer to future projects and I don't really know much about JSON. Once again thank you so much, I expected to have to spend hours trying to get this to work today! Mat On Dec 5, 11:55 am, Michael Geary [EMAIL PROTECTED] wrote: Hi Mat, 1) You're defining towncity like this: var towncity = window.towncity = new Array(); That creates both a local variable named towncity and a window property (global variable) of the same name. Is that what you want? Do you need to use towncity outside this code? If not, I would change it to: var towncity = []; 2) In the .each() inside your ajax callback you have this code: towncity = $(this).text(); That *replaces* the towncity variable with the text of the single XML element for the current iteration of .each() - so it's no longer an array but is now a simple text string. It doesn't sound like that's what you want, is it? To append the item text to the towncity array, you could change it to: towncity.push( $(this).text() ); But you probably also want to clear this array before running the loop (is that right?), so just before the $(xml).find(...) you should add: towncity = []; // note: no var here which gives you this code: success: function(xml) { towncity = []; $(xml).find(...).map(function(){ towncity.push( $(this).text() ); }); } Given that, you could simplify the code to: success: function(xml) { towncity = $(xml).find(...).map(function(){ return $(this).text(); }); } BTW, do you have control over the XML file that the server generates? If you do, you could use JSON instead of XML to make the code simpler. If you're stuck with XML, this code should do the trick. -Mike From: Mat Hi there, I'm sorry this is a pretty newbie question I am using JQuery with an xml file and autocomplete. What I am trying to achieve is to use an xml file as my data source to autocomplete cities in a form once a user selects their province. When a user selects a particular province then only the cities in that province will be listed by the autocomplete script as the user starts to type in the 'city' form field. My problem here is that I am trying to use the array 'towncity' as my data source for autocomplete and change the contents of the array when the province select box #province is changed. However, I can not get my $('#province').change(function() to affect the array 'towncity' that I have declared outside of the function script type=text/javascript $(document).ready(function() { var towncity = window.towncity = new Array(); $(#city).autocomplete(towncity); $.preloadCssImages(); $('div.jshide').show(); $(#tenantForm).validate({ rules: { name: { required: true, minlength: 2 }, province:required, ccom:required, occupied: required, rented:required, condo:required, payment:required } }); $(#renewdate).datepicker({ dateFormat: d M, yy, showOn: both, buttonImage: images/calendar.gif, buttonImageOnly: true }); $('#province').change(function() { var currprov = $('option:selected', this).text(); $(function() { $.ajax({ type: GET, url: xml/location.xml, dataType: xml, success: function(xml) { $(xml).find([EMAIL PROTECTED]'+ currprov +'] TOWN_CITY_NAME).each(function(){ towncity = $(this).text(); }); } });
[jQuery] Re: Variable scope: Newbie Question
One thing I do notice with my code is that it is slow. If I change provinces and type in the city field and change provinces again things slow right down. I know this must be due to the way I have coded this. I am wondering if you have any suggestion to improve the speed of things? The form will primarily used by those in Alberta so I though if I loaded the array with Alberta city names by default when the script loads it might speed things up. DO you think the JSON approach you mentioned would be quicker? Thanks, Mat On Dec 6, 12:15 pm, Mat [EMAIL PROTECTED] wrote: Hi Micheal, Thank you so much for that. I knew I was getting close to a solution but I was well and truly stuck. It is now working and I am delighted. This is the code that worked for me success: function(xml) { towncity = []; $(xml).find([EMAIL PROTECTED]'+ currprov +'] TOWN_CITY_NAME).map (function(){ towncity.push( $(this).text() ); $(#city).autocomplete(towncity); }); } The XML file I am querying is a file I constructed myself (so I have full access to it) for a few different reasons. I am not good enough at mySQL to create a database with the information, I am too cheap to pay for a ready made database ;), the autocomplete script gives an option of storing the data in a local.js file but I did not like this idea as it may not transfer to future projects and I don't really know much about JSON. Once again thank you so much, I expected to have to spend hours trying to get this to work today! Mat On Dec 5, 11:55 am, Michael Geary [EMAIL PROTECTED] wrote: Hi Mat, 1) You're defining towncity like this: var towncity = window.towncity = new Array(); That creates both a local variable named towncity and a window property (global variable) of the same name. Is that what you want? Do you need to use towncity outside this code? If not, I would change it to: var towncity = []; 2) In the .each() inside your ajax callback you have this code: towncity = $(this).text(); That *replaces* the towncity variable with the text of the single XML element for the current iteration of .each() - so it's no longer an array but is now a simple text string. It doesn't sound like that's what you want, is it? To append the item text to the towncity array, you could change it to: towncity.push( $(this).text() ); But you probably also want to clear this array before running the loop (is that right?), so just before the $(xml).find(...) you should add: towncity = []; // note: no var here which gives you this code: success: function(xml) { towncity = []; $(xml).find(...).map(function(){ towncity.push( $(this).text() ); }); } Given that, you could simplify the code to: success: function(xml) { towncity = $(xml).find(...).map(function(){ return $(this).text(); }); } BTW, do you have control over the XML file that the server generates? If you do, you could use JSON instead of XML to make the code simpler. If you're stuck with XML, this code should do the trick. -Mike From: Mat Hi there, I'm sorry this is a pretty newbie question I am using JQuery with an xml file and autocomplete. What I am trying to achieve is to use an xml file as my data source to autocomplete cities in a form once a user selects their province. When a user selects a particular province then only the cities in that province will be listed by the autocomplete script as the user starts to type in the 'city' form field. My problem here is that I am trying to use the array 'towncity' as my data source for autocomplete and change the contents of the array when the province select box #province is changed. However, I can not get my $('#province').change(function() to affect the array 'towncity' that I have declared outside of the function script type=text/javascript $(document).ready(function() { var towncity = window.towncity = new Array(); $(#city).autocomplete(towncity); $.preloadCssImages(); $('div.jshide').show(); $(#tenantForm).validate({ rules: { name: { required: true, minlength: 2 }, province:required, ccom:required, occupied: required, rented:required, condo:required, payment:required } }); $(#renewdate).datepicker({ dateFormat: d M, yy, showOn: both, buttonImage: images/calendar.gif, buttonImageOnly: true
[jQuery] Re: Variable scope: Newbie Question
Wow I'm chatty aren't I... I just wanted to add I changed my code to this $(function() { $.ajax({ type: GET, url: xml/location.xml, dataType: xml, success: function(xml) { towncity = []; $(xml).find([EMAIL PROTECTED]'+ currprov +'] TOWN_CITY_NAME).map(function(){ towncity.push( $(this).text() ); }); $(#city).autocomplete(towncity); } and that improved speed greatly. It appeared I was binding the autocomplete script and data source to the #city field with every iteration of my XML file query and this of course was causing a huge speed bump. Once I moved the autocomplete binding statement outside of my XML file query function the wheels turned much faster. Mat :) On Dec 6, 12:26 pm, Mat [EMAIL PROTECTED] wrote: One thing I do notice with my code is that it is slow. If I change provinces and type in the city field and change provinces again things slow right down. I know this must be due to the way I have coded this. I am wondering if you have any suggestion to improve the speed of things? The form will primarily used by those in Alberta so I though if I loaded the array with Alberta city names by default when the script loads it might speed things up. DO you think the JSON approach you mentioned would be quicker? Thanks, Mat On Dec 6, 12:15 pm, Mat [EMAIL PROTECTED] wrote: Hi Micheal, Thank you so much for that. I knew I was getting close to a solution but I was well and truly stuck. It is now working and I am delighted. This is the code that worked for me success: function(xml) { towncity = []; $(xml).find([EMAIL PROTECTED]'+ currprov +'] TOWN_CITY_NAME).map (function(){ towncity.push( $(this).text() ); $(#city).autocomplete(towncity); }); } The XML file I am querying is a file I constructed myself (so I have full access to it) for a few different reasons. I am not good enough at mySQL to create a database with the information, I am too cheap to pay for a ready made database ;), the autocomplete script gives an option of storing the data in a local.js file but I did not like this idea as it may not transfer to future projects and I don't really know much about JSON. Once again thank you so much, I expected to have to spend hours trying to get this to work today! Mat On Dec 5, 11:55 am, Michael Geary [EMAIL PROTECTED] wrote: Hi Mat, 1) You're defining towncity like this: var towncity = window.towncity = new Array(); That creates both a local variable named towncity and a window property (global variable) of the same name. Is that what you want? Do you need to use towncity outside this code? If not, I would change it to: var towncity = []; 2) In the .each() inside your ajax callback you have this code: towncity = $(this).text(); That *replaces* the towncity variable with the text of the single XML element for the current iteration of .each() - so it's no longer an array but is now a simple text string. It doesn't sound like that's what you want, is it? To append the item text to the towncity array, you could change it to: towncity.push( $(this).text() ); But you probably also want to clear this array before running the loop (is that right?), so just before the $(xml).find(...) you should add: towncity = []; // note: no var here which gives you this code: success: function(xml) { towncity = []; $(xml).find(...).map(function(){ towncity.push( $(this).text() ); }); } Given that, you could simplify the code to: success: function(xml) { towncity = $(xml).find(...).map(function(){ return $(this).text(); }); } BTW, do you have control over the XML file that the server generates? If you do, you could use JSON instead of XML to make the code simpler. If you're stuck with XML, this code should do the trick. -Mike From: Mat Hi there, I'm sorry this is a pretty newbie question I am using JQuery with an xml file and autocomplete. What I am trying to achieve is to use an xml file as my data source to autocomplete cities in a form once a user selects their province. When a user selects a particular province then only the cities in that province will be listed by the autocomplete script as the user starts to type in the 'city' form field. My
[jQuery] Re: Variable scope: Newbie Question
Hi Mat, 1) You're defining towncity like this: var towncity = window.towncity = new Array(); That creates both a local variable named towncity and a window property (global variable) of the same name. Is that what you want? Do you need to use towncity outside this code? If not, I would change it to: var towncity = []; 2) In the .each() inside your ajax callback you have this code: towncity = $(this).text(); That *replaces* the towncity variable with the text of the single XML element for the current iteration of .each() - so it's no longer an array but is now a simple text string. It doesn't sound like that's what you want, is it? To append the item text to the towncity array, you could change it to: towncity.push( $(this).text() ); But you probably also want to clear this array before running the loop (is that right?), so just before the $(xml).find(...) you should add: towncity = []; // note: no var here which gives you this code: success: function(xml) { towncity = []; $(xml).find(...).map(function(){ towncity.push( $(this).text() ); }); } Given that, you could simplify the code to: success: function(xml) { towncity = $(xml).find(...).map(function(){ return $(this).text(); }); } BTW, do you have control over the XML file that the server generates? If you do, you could use JSON instead of XML to make the code simpler. If you're stuck with XML, this code should do the trick. -Mike From: Mat Hi there, I'm sorry this is a pretty newbie question I am using JQuery with an xml file and autocomplete. What I am trying to achieve is to use an xml file as my data source to autocomplete cities in a form once a user selects their province. When a user selects a particular province then only the cities in that province will be listed by the autocomplete script as the user starts to type in the 'city' form field. My problem here is that I am trying to use the array 'towncity' as my data source for autocomplete and change the contents of the array when the province select box #province is changed. However, I can not get my $('#province').change(function() to affect the array 'towncity' that I have declared outside of the function script type=text/javascript $(document).ready(function() { var towncity = window.towncity = new Array(); $(#city).autocomplete(towncity); $.preloadCssImages(); $('div.jshide').show(); $(#tenantForm).validate({ rules: { name: { required: true, minlength: 2 }, province:required, ccom:required, occupied: required, rented:required, condo:required, payment:required } }); $(#renewdate).datepicker({ dateFormat: d M, yy, showOn: both, buttonImage: images/calendar.gif, buttonImageOnly: true }); $('#province').change(function() { var currprov = $('option:selected', this).text(); $(function() { $.ajax({ type: GET, url: xml/location.xml, dataType: xml, success: function(xml) { $(xml).find([EMAIL PROTECTED]'+ currprov +'] TOWN_CITY_NAME).each(function(){ towncity = $(this).text(); }); } }); }); }); }); /script Anyone have any ideas? Thanks, Mat
[jQuery] Re: Variable Scope
I tried it out and it fixes the problem - thanks a ton Michael!
[jQuery] Re: Variable Scope
Thanks Michael. I'll try that out and see where I get!
[jQuery] Re: Variable Scope
So what exactly is the question/problem with variable scope? Are you losing the scope somewhere? Are you asking if there's a better way? it's not clear at all On Oct 8, 10:00 pm, QuickScriptz [EMAIL PROTECTED] wrote: So I've been over my code again and again and I've scoured through the Wiki and Help Documentation but I still cannot seem to make it work. I have a row of icons and the idea is when you mouseover, a popup (p) appears below it and then when you mouseout, it fades again. I've found the best way to do it is that start with all the popups to the side of the icons (so you can still hover over the icons and the popups don't just block your way) and the popups begin as hidden (opacity: 0). When you mouseover the icons, it sets the top and left attribute of the popup to just below the icon and then it slowly fades the popup from 0 to .7 and then vice versa when mouseout. So, here is my code. You can view the product at the site below. Any suggestions?http://dev.quickscriptz.ca/v4/index.php script type=text/javascript //![CDATA[ $(document).ready(function(){ // PNG transparency fix $(document).pngFix(); // Basic variables var outSpeed = medium; var outOpacity = .7; var inSpeed = fast; var inOpacity = 1; // Variables for icons popups var nowIcon, nowPopup, topPx, leftPx, topPxH, leftPxH, topPxS, leftPxS; // Loop it five times for(var i = 1; i = 5; i++){ // Variable for icon id nowIcon = #icon + i; nowPopup = #popup + i; // Height from top of icon topPx = $(nowIcon).css(top); leftPx = $(nowIcon).css(left); // Popup hidden position topPxH = topPx - 10; leftPxH = leftPx - 150; // Popup showing position topPxS = topPx + 100; leftPxS = leftPx - 50; // Start by hiding popups $(nowPopup).css({top: topPxH}); $(nowPopup).css({left: leftPxH}); // Set opacity to zero (invisible) //$(nowPopup).animate({opacity: 0}); // Mouse over event $(nowIcon).mouseover(function(){ $(this).fadeTo(outSpeed, outOpacity); $(nowPopup).css({top: topPxS}); $(nowPopup).css({left: leftPxS}); $(nowPopup).fadeTo(outSpeed, outOpacity); }) // Mouse out event $(nowIcon).mouseout(function(){ $(this).fadeTo(inSpeed, inOpacity); $(nowPopup).fadeTo(inSpeed, 0); }) } }) //]]/script
[jQuery] Re: Variable Scope
I have a row of icons and the idea is when you mouseover, a popup (p) appears below it and then when you mouseout, it fades again. There are a lot of plugins that do this, like tooltip, cluetip and jtip. Did you want to do something special? $(nowPopup).css({left: leftPxS}); The closure is working as it should, but there is only one nowPopup variable and by the time any of the mouseover/mouseout events fire it is the same value for all the elements you've attached it to. Definitely take a look at one of the tip plugins.
[jQuery] Re: Variable Scope
Sorry about that MorningZ. My original question actually had to do with whether somehow the value of the variable was being lost because of the fact that when I went to actually use the variable it was nested inside some other code blocks but what Dave said answers my question. The closure is working as it should, but there is only one nowPopup variable and by the time any of the mouseover/mouseout events fire it is the same value for all the elements you've attached it to. So, you're saying that basically, each time it runs through the for loop it doesn't actually like print out the code and replace the variables with their values, but it just cycles through the code X number of times and the variables only become actual values when the function (mouseover) is called? I see what you're saying but if that was in fact the case then shouldn't it be that the icons don't fade either? And I will look into the tooltip plugins.
[jQuery] Re: Variable Scope
A loop doesn't print out the code. A function call *does*, in a manner of speaking. I didn't look at the rest of your code in any detail, but if you want the loop to work more the way you're expecting, where it saves the individual loop values for i and the other variables you set up inside the loop, simply change the loop code to: for(var i = 1; i = 5; i++) addPopup( i ); And then add the function: function addPopup( i ) { // all the code in the body of the existing for loop goes here } Figure out why that makes a difference and you will understand closures. :-) -Mike From: QuickScriptz So, you're saying that basically, each time it runs through the for loop it doesn't actually like print out the code and replace the variables with their values, but it just cycles through the code X number of times and the variables only become actual values when the function (mouseover) is called?