Uncaught ReferenceError: i is not defined

I'm trying to make a for-loop base on my array

var lists = [ "a", "b", "c", "d" ];


JS

for ( i = 0; i < lists.length; i++) { // console.log(lists[i]); $(".sa-report-btn-"+lists[i] ).click(function () { $(".sa-hide-"+lists[i]).removeClass("hidden"); $(".sa-report-"+lists[i]).addClass("hidden"); }); $(".sa-hide-btn-"+lists[i]).click(function () { $(".sa-hide-"+lists[i]).addClass("hidden"); $(".sa-report-"+lists[i]).removeClass("hidden"); }); }

Am I doing it correctly ? I got Uncaught ReferenceError: i is not defined Can I concat each loop with my jQuery selector like this --> $(".sa-hide-"+lists[i]) ? just curious ...

-------------Problems Reply------------

First off, it sounds like you're using strict mode — good! It's saved you from falling prey to The Horror of Implicit Globals.

There are two issues with the code.

The first one is that you're missing the declaration for i. You need to add var i; above the loop, e.g:

var i;
for ( i = 0; i < lists.length; i++) {
// ...

or

for (var i = 0; i < lists.length; i++) {

Note, though, that even in that latter example, the i variable is function-wide, not limited to the for loop.

The second one is more subtle, and is outlined in this question and its answers: Your click handlers will have an enduring reference to the i variable, not a copy of it as of where they were created. So when they run in response to a click, they'll see i as the value lists.length (the value it has when the loop has finished).

In your case, it's really easy to fix (and you don't have to declare i anymore): Remove the loop entirely, and replace it with Array#forEach or jQuery.each:

lists.forEach(function(list) {

$(".sa-report-btn-" + list).click(function () {
$(".sa-hide-" + list).removeClass("hidden");
$(".sa-report-" + list).addClass("hidden");
});

$(".sa-hide-btn-" + list).click(function () {
$(".sa-hide-" + list).addClass("hidden");
$(".sa-report-" + list).removeClass("hidden");
});
});

If you need to support really old browsers, you can either shim Array#forEach (which was added in 2009, as part of ECMAScript5), or you can use $.each (jQuery.each) instead:

$.each(lists, function(index, list) {
// Note addition ------^
$(".sa-report-btn-" + list).click(function () {
$(".sa-hide-" + list).removeClass("hidden");
$(".sa-report-" + list).addClass("hidden");
});

$(".sa-hide-btn-" + list).click(function () {
$(".sa-hide-" + list).addClass("hidden");
$(".sa-report-" + list).removeClass("hidden");
});
});

Note that we don't actually use index anywhere in our callback, but we have to specify it because $.each calls our callback with the index as the first argument, and the value as the second. (Which is why I prefer Array#forEach.) So we have to accept two arguments, with the one we want being the second one.

Category:javascript Views:77 Time:2019-03-20

Related post

  • Uncaught ReferenceError: pageTracker is not defined 2010-07-04

    You'll have to forgive me on this one. I understand that the issue is probably very simple, but I'm not a JS coder and am only just starting to get to grips with jQuery. So I have a jQuery Ajax call in $(document).ready: $('#newesttab').click(functio

  • JavaScript: Uncaught ReferenceError: confirm_Logout is not defined (anonymous function) 2010-12-07

    So I'm pretty new to javascript...right now I'm just writing that dynamic logout button that will go log the user out before reloading the page. I wrote the function (this is actually my entire script.js file): var scriptLoaded = true; function confi

  • uncaught referenceerror function is not defined in $(document).ready(function(){} 2011-02-21

    I have this uncaught referenceerror function is not defined error which do not understand. If I have $(document).ready(function(){ function codeAddress() { var address = document.getElementById("formatedAddress").value; geocoder.geocode( { 'address':

  • Uncaught ReferenceError: loadNext is not defined (anonymous function) 2011-02-22

    I am getting this error Uncaught ReferenceError: loadNext is not defined (anonymous function) The line that is causing this is <img name="imageLoad" class="hiddenPic" src="<?php echo "albums/$folder/$startImage"; ?>" onLoad="javascript:loadN

  • Uncaught ReferenceError: doit is not defined 2011-04-18

    I'm writing a small userscript to include a link next to user's profile image for a phpBB forum that I frequent. On clicking the link, I'm getting an error like below: Uncaught ReferenceError: doit is not defined (anonymous function) viewtopic.php:54

  • Uncaught ReferenceError: Lawnchair is not defined 2011-06-06

    I'm trying to get the basic lawnchair example working. The Code: <script type="text/javscript" src="http://westcoastlogic.com/lawnchair/src/lawnchair.js"></script> <script type="text/javascript"> var people = new Lawnchair('people')

  • Javascript Uncaught ReferenceError: Class is not defined 2011-06-08

    I am trying to implement a moving photo slider that is no jQuery , it uses moo tools I want a slider like this guy http://mahusay-fbt.blogspot.com/ So I got that piece of code that is specifically designed for blogger here bit.ly/chXo9Q I implemented

  • Javascript Uncaught ReferenceError: parameter is not defined 2011-06-17

    I have some Javascript code: function addRow(tableID, rowId) { var table = document.getElementById(tableID); var rowPosition = document.getElementById(rowID).rowIndex; //etc. } But this throws a Javascript error "Uncaught ReferenceError: rowID is not

  • Uncaught ReferenceError: X is not defined 2011-07-13

    So I am digging through the WebOS enyo framework and am getting very frustrated. I am currently getting the following error in my log. I have been looking at the samples in the framework and I just can't seem to find where the error is stemming from.

  • Uncaught ReferenceError: parseURL is not defined 2011-07-27

    I've defined a function named parseURL in javascript in the head of my file, and I have a button set so that when it is clicked, it should call said function. However, for some reason my debugger is telling me that parseURL is not defined. The exact

  • Greasemonkey Uncaught ReferenceError: initScript is not defined in Chrome only 2011-10-13

    The code below, Greasemonkey script, works in Firefox and Opera. Also when packaged for Safari it works fine. When run in Chrome however I get Uncaught ReferenceError: initScript is not defined. Everything seems to work fine right up until initScript

  • Uncaught ReferenceError:foobar is not defined (anonymous function) 2011-12-19

    I have this js file serving from some domain say foobar.com at http://foobar.com/static/js/main.js: $(document).ready(function() { function foobar(bar){ $.ajax({ url: "/site/foo/", data: {'foo':bar}, dataType: "jsonp", crossdomain: !0, success: funct

  • Uncaught ReferenceError: getElementById is not defined at null:1 2012-01-21

    I am trying to get the contents of hiddenDivHL which is present in the part of the following HTML page : <div id='hiddenDivHL' style='display:none'>http://74.127.61.106/udayavaniIpad/details.php?home=0&catid=884&newsid=123663[InnerSep]h

  • Uncaught ReferenceError: hello is not defined 2012-02-28

    Any idea why I have the error Uncaught ReferenceError: hello is not defined ? function hello() { console.log('hello ()'); setTimeout("hello ()", 1000); } setTimeout("hello()", 1000);​ Here is a jsfiddle : http://jsfiddle.net/s9vLk/ --------------Solu

  • Uncaught ReferenceError: initialize is not defined 2012-03-07

    I am trying to render multiple custom markers on a page using web2py's framework and my map will not render. Using chrome's debugger, I see two errors, one says "Uncaught SyntaxError: Unexpected token <" and the second one says "Uncaught Reference

  • Uncaught ReferenceError: Class is not defined? 2012-03-08

    I'm curious to know why I'm getting this error? I've copied it exact from the website beezid.com (carousel.js) file, and I'm trying to get the same slide as them onto my website to update it.. As you can see I'm having issues with this?? Their site d

  • "Uncaught ReferenceError: JQueryValidatorUI is not defined"? 2012-03-09

    "Uncaught ReferenceError: JQueryValidatorUI is not defined" when using jquery-validation-ui plugin ? also Uncaught TypeError: Object [object Object] has no method 'validate' Here's my order of scripts: <script src="http://code.jquery.com/jquery-1.

  • Uncaught ReferenceError: _gaq is not defined (Google Analytics) 2012-05-01

    the following message appears when viewing a site page in the chrome debug log. "Uncaught ReferenceError: _gaq is not defined" the page itself is supposed to track an object using the 'onload' event handler and fire a '_trackEvent' for Google Analyti

  • Uncaught ReferenceError: getWidget is not defined 2013-01-29

    I'm trying to call a function in index.php but I get this error Uncaught ReferenceError: getWidget is not defined. When I call the function in the widget.php it works. How can I get the function getWidget(); to work in index.php? I also get this warn

  • Uncaught ReferenceError: _ is not defined from restangular 2013-06-24

    I'm getting this error: Uncaught ReferenceError: _ is not defined from restangular when trying to use Restangular. HTML <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script> <script type="text/jav

  • Missing cordova.js and Uncaught ReferenceError: Media is not defined 2014-03-12

    So I have created an from scratch app using the latest version of Cordova and followed the instructions from the Cordova API documentation. I am trying to get a very basic mp3 player working on Android, so I have installed the Android platform and in

  • DataTable Error: Uncaught ReferenceError: jQuery is not defined 2014-08-27

    My datatable plugin is not working and i dont know why please help... when trying to debug the javascript on Google crome i found this error and i know if they are clashing Uncaught ReferenceError: jQuery is not defined localhost:49769/Scripts/main.j

  • Javascript : Uncaught ReferenceError: calculator_test is not defined 2014-09-18

    what am I missing I've got error message : Uncaught ReferenceError: calculator_test is not defined index.html: <!DOCTYPE html> <html> <body> <p>Click the button</p> <button onclick="calculator_test()">test</butt

  • uncaught referenceError: sKey is not defined onkeydown in chrome 2015-02-23

    I am having a hard time with this script... I have a html form name="mainF" that has two input->submit inside the form.. The first submit is in a navigation that has a position of fixed that floats on top of the page and every page through mvc. Wh

  • Uncaught ReferenceError PrimeFaces is not defined in my Google Console 2016-02-14

    I know there are several stack-topics which are exact same of mine, but didn't get how to solve that issue in my Chrome console. Please note that currently things are displayed correctly, it's just I would solve anything in my project. Pressing F12 i

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.158 (s). 11 q(s)