简体   繁体   中英

In Javascript, Value not comming instead the variable name is displayed

function ProvideValue(){

    Values = document.getElementById('HiddenValue').value;

FirstCut = Values.split("@#@"); // This will return the array ID@-@VALUE@-@TYPE

    var CtrlId;
    for (i = 0; i < FirstCut.length - 1; i++) {

        Strings = FirstCut[i];
        SecondCut = Strings.split("@-@");

        if(SecondCut[2].match("TEXT")) {
            CtrlId = "" + SecondCut[0];
            document.getElementById(CtrlId).value = SecondCut[1];
        }
    }
}

This is my code instead of the Id, which i can print it.But CtrlId is not replaced by the actual value. Am getting error document.getElementById(CtrlId).value is NULL . I tried to hard code the ID then its working fine but i cannot hard code the controlsID because there are 1000s of control and everytime the ID changes.

Your code seems fine (apart from implied globals 1 ), you must have some other problem in your HTML document... I'm also not sure why you're leaving out the last value from the first cut since you're interating to length - 2 , because i is less than length - 1 (not less than or equal ) which means that it goes all the way to value length - 2 and then breaks the loop.

Here's a JSFiddle I created that uses your code and displays some additional console messages and actually applies values to inputs as provided by the hidden input.

1 Important

I applied var to your variables so they're not implied globals which should be avoided at all times because they're nothing but evil friend of hidden bugs.

The code I used

HTML is super simple but I do have both elements with IDs that are being addressed in the compound value of the hidden field:

<input type="hidden" id="hidden" value="me@-@Rob@-@text@#@you@-@Mike@-@text" />
<input id="me" value="name" />
<input id="you" value="name" />​

Script is simple as well (runs on DOM ready for JSFiddle simplicity reasons):

var vals = document.getElementById('hidden').value;

var firstCut = vals.split("@#@");

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

    var ctrl = firstCut[i].split("@-@");

    if (ctrl[2].match("text")) {
      var id = ctrl[0];
      document.getElementById(id).value = ctrl[1];
    }
}​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM