Need Help with Using KM Variables in JavaScript

I cannot duplicate this behavior you see. What I see is that the JavaScript is reading/getting the KM Variable just fine:

Screenshot from the Chrome Dev Tools:

scriptResults = document.kmvar.vDropdownInput;

image

I didn't change your script, but I did put it in a function and add a few lines at the top.
Here's the script I ran/debugged:

'use strict';
(function myMain() {      // this will auto-run when script is executed

var scriptResults = 'TBD'

debugger;

scriptResults = document.kmvar.vDropdownInput;

// variable to enter into dropdown
var vDropdownInput = ("\""+document.kmvar.vDropdownInput+"\"");

// variable to get the Element by Name
var objSelect = document.getElementById("web-selection_"+document.kmvar.vZEROIndex+"_");


// function to do the work
setSelectedValue(objSelect, vDropdownInput);


// function definition
function setSelectedValue(object, value) {
    for (var i = 0; i < object.options.length; i++) {
        if (object.options[i].text === value) {
            object.options[i].selected = true;
            // object.onchange();
         //   vDropdownInput;
            return;

    }
}
    // Throw exception if option `value` not found.
    var tag = object.nodeName;
    var str = value;

    return str;
}

return scriptResults;
}  // END of function myMain()
)();  // autorun

I also run this simple test, which works fine:

var kmVarStr = document.kmvar.vDropdownInput;
alert('kmVar: ' + kmVarStr);
kmVarStr;

Since I don't have access to your web page, I can't really debug, but this statement does not look correct to me:

// variable to get the Element by Name
var objSelect = document.getElementById("web-selection_"+document.kmvar.vZEROIndex+"_");

First of all, you do NOT set a KM Variable named "vZEROIndex", so this statement would fail just based on that.

If you can't share the URL, can you upload the HTML code (in a Code Block) of the main part of the web page you are trying to use.

Let me be clear: The issue has NOTHING to do with getting KM Variables into JavaScript. That is clearly demostrated by my script.

I'd suggest that you use the Chrome debugger. Open the web page of interest, then open the Chrome Dev Tools (⌘⌥I) for that page, reselect the web page, and run my script which has the debugger enabled. Then you can step through the code to see where it fails.

Example of Chrome Debugger

1 Like