0

I have the following JS code, I feel weird that only the first for loop can run, but the 2nd part doesn't work. I even tried to make two different if statement and include the for loop separately, but the same thing happened. If I run the for loop separately (by deleting another for loop), both of them can run, means both of the logic should be correct. Please help.

var s = "<?php printf($resultDataOrderInfo[0][status]); ?>";

   if(s == "Processing"){
       var t = document.getElementsByTagName("input");
       for (i=0; i<=t.length; i++){
           t[i].setAttribute("readonly","true");
       }  // only this above part can run

       var d = document.getElementsByName("delete");
       for (i=0; i<=d.length; i++){
           d[i].setAttribute("hidden","true");
       }
   }
10
  • 4
    There's no reason they shouldn't be both be able to run. Can you reproduce this issue in a jsFiddle ? Commented May 5, 2014 at 22:41
  • 1
    "doesn't work" is bad explanation - please use debugger and step through the code to provide good details in the post. (F12 will bring dev tools in most desktop browsers) Commented May 5, 2014 at 22:45
  • 2
    Are you sure d.length != 0 ? Commented May 5, 2014 at 22:45
  • 2
    @stackErr - why using new variable matters? it is global variable anyway, should not really matter if used in one or both loops as it is initialized to 0 anyway in both cases. Commented May 5, 2014 at 22:46
  • 1
    @stackErr: It can't be changed by async code. Async code is unable to break into the current synchronous execution of code. Even if it's timed such that it would have landed at that exact time, it has to wait. If that wasn't the case, then using a separate variable name wouldn't help since the async code could break in during the loop as well. Commented May 5, 2014 at 23:05

1 Answer 1

2

I think you want to change all of the <= to <. If length is equal to 0, then it is going to execute once, but fail due to the length being zero. Which, I believe is the issue of it not reaching the second for loop, due to an error occurring on the first.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually, I don't think it matters whether or not t.length is 0.
Thank you Christopher. By changing all <= to <, both of of the loop work. Since I know both t.length and d.length are not 0, but I think the script paused on error because if I write i<=t.length, when i=t.length, the script can't actually find the t[i] tag, because it doesn't exist, then the script hangs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.