www.webdeveloper.com
Results 1 to 3 of 3

Thread: variable scope what wrong?

  1. #1
    Join Date
    Jan 2012
    Posts
    2

    variable scope what wrong?

    Hi all,
    I am sucking with this problem over 4 hours and couldn't find an answer. Here is the code:
    Code:
    var inputCheck = document.getElementsByTagName("input");
    	for( i = 0; i < inputCheck.length; i++) {
    		inputCheck[i].onclick = function() {		
    			inputCheck[i].setAttribute('select', 'ok');
    		}
    	}
    When I run this code I get an error: TypeError: inputCheck[i] is undefined.
    I don't know because, the variable i that I defined in for loops is in global scope, so I think the anonymous function that is attached to onclick event CAN access it.
    However, I got that error on firebug.
    Could someone help me point out what's wrong in this situation?
    Thank you!

  2. #2
    Join Date
    Nov 2010
    Posts
    1,082
    it's called function closure. Basically, when the click happens, the loop has finished running, and i has the value of inputCheck.length, and there is no element which relates to inputCheck[inputCheck.length].

    And even if there were, it wouldn't be the one you were trying to access.

    Have a look here, at the section titled "The Infamous Loop Problem"
    Last edited by xelawho; 09-04-2012 at 12:17 PM.

  3. #3
    Join Date
    Jul 2011
    Posts
    24
    Code:
    var inputCheck = document.getElementsByTagName("input");
    	for( i = 0; i < inputCheck.length; i++) {
    		inputCheck[i].onclick = function() {		
    			this.setAttribute('select', 'ok');
    		}
    	}

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles