Is this the incorrect syntax? I'm trying to find which in a series of 5 IDs is not set.
Code:for (i=1;i<=6;i++) { if (document.getElementById('inactive' + i) === null) { alert("it is" +i); } }
Is this the incorrect syntax? I'm trying to find which in a series of 5 IDs is not set.
Code:for (i=1;i<=6;i++) { if (document.getElementById('inactive' + i) === null) { alert("it is" +i); } }
Last edited by bluewalrus; 11-22-2010 at 12:17 AM.
Corrections to my coding/thoughts welcome.
you mean "inactive1", "inactive2", etc.? Just "if" works:Code:for (i=1; i<6; i++) { if(!document.getElementById('inactive' + i){ alert('it is ' + i); } }
bluewalrus (11-19-2010)
You should declare the variable i. In this context ++i (pre-increment) is more efficient than i++ (post-increment). Also, and Adrian corrects this in his code but doesn't mention it, there is a difference between+iand+ i. The former means "positive i" and is roughly equivalent toparseFloat(i)or1 * i. In the context of the code, this would be a syntax error. The latter means "plus i" (in this context "concat the string 'it is' and the value of i). So that's the big no no in the original code. In the alert I think you want a space after "is". If we don't want a bunch of alerts in cases where - say only inactive1 exists, we should return from the function. So we could then have:
But, as Adrian points out, such a strict test of the element isn't required. What he doesn't mention is that it might fail in some cases (though I'm not certain of that, if it doesn't it's preferred for efficiency's sake). In any case his solution works:Code:for (var i = 1; i <= 6; ++i) { if (document.getElementById('inactive' + i) === null) { alert("it is " + i); return; } }
Note: Looking back over this I realized that this code might not be in a function, or even if it is we might not want the function to return just because it 'finds' a missing element. If that's the case we can substituteCode:for (var i = 1; i <= 6; ++i) { if (!document.getElementById('inactive' + i)){ alert("it is " + i); return; } }break;forreturn;- That way it will break out of the loop regardless of whether or not the loop is inside a function or not and continue processing after the closing brace of the for statement.
Last edited by jscheuer1; 11-20-2010 at 05:28 AM. Reason: English usage, later add note
- John________________________
Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate
bluewalrus (11-19-2010),traq (11-19-2010)
thanks John, javascript isn't my strong suit (I'm really just now starting to get comfortable) - what I offered was based solely on testing and finding out it worksThe things I "didn't mention," I didn't know. Thanks for expounding!
Yup that did it. Thanks.
Corrections to my coding/thoughts welcome.
Bookmarks