开发者

How to use counter variable in if condition?

I want to use counter variable in IF condition..I tried but its not working.Please help me with correct code.. code is:

var ChForAtn=0;
if(arrayAtnd[ChForAtn]=="Name")
{                
    alert("Name");
    if(document.forms[7].ckbx'+ChForAt开发者_运维问答n+'.checked==true)
    {
        alert('Name added and checked also');
    }
    ChForAtn++;
}


var ChForAtn=0;  <--- Variable declared as 0
if(arrayAtnd[ChForAtn]=="Name")
{                
    alert("Name");
    if(document.forms[7].ckbx'+ChForAtn+'.checked==true) <-- You have your concatenation wrong.
    {
        alert('Name added and checked also');
    }
    ChForAtn++; <--- Variable incremented
}

First off, you should post your loop. The code snippet you posted doesn't contain a loop.

The only incremented variable you have in this code is reset at the top of the code, which doesn't make much sense for this fragment.

EDIT

The following won't work because you have your concatenation mixed up

document.forms[7].ckbx'+ChForAtn+'.checked==true

I'm not any too good with JS, but if you're trying to make a variable variable like in PHP, you'd have to use something like eval(). I know you can access it via window[] but this might not be possible in this case.

A solution with eval()

if (eval('document.forms[7].ckbx' + ChForAtn + '.checked') == true) {
  //code
}

NOTE There are good reasons why you shouldn't use eval(). Have a look here for more information : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/eval#Don.27t_use_eval.21

However, given your use case I don't really see a way around it. I would welcome alternative suggestions from other posters.

EDIT2

As @nickf points out in the comments, you can do the same thing by calling

if (document.forms[7]['ckbx' + ChForAtn].checked == true) {
   //code
}

A cautionary tale for others, don't use eval() where avoidable :)


Use a for loop in the if condition.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜