1

I have a HTML Listbox and I need to add values to it on the page load. I have tried to call a JS function on page load event on both <body> tag and <select> tag but it does not execute the the function.

<body onload='popListbox(<%=session.getAttribute("objNames")%>)'>

<select id="lstObjects" onload='popListbox(<%=session.getAttribute("objNames")%>)'>

If I try onclick it executes fine but not in onload event. Can someone help me with this.?

UPDATE: my JS function

function popListbox(objList){

var select = document.getElementById("lstObjects");
var objects = objList;
var objects_array = [];
for(var i in objects) {
    if(objects.hasOwnProperty(i) && !isNaN(+i)) {
        objects_array[+i] = objects[i];
    }
}
for(var i = 0; i < objects_array.length; i++) {
    var opt = objects_array[i];
    var el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    select.appendChild(el);
}

}

SajithRu
  • 225
  • 1
  • 8
  • 24

2 Answers2

0

try document.ready

$( document ).ready(function() {

//your code here

});

Amarnath R Shenoy
  • 5,121
  • 8
  • 24
  • 32
-1

What's the JS function? I suspect, because only the body tag has an onload handler, perhaps your js function is not aware of the element context when it is triggered from document root.

function popListbox(objList){
var select = document.getElementById('lstObjects');
for(i=0,ic=objList.length;i<ic;++i) {
    var el=document.createElement('option');
    el.textContent=objList[i];
    el.value=objList[i];
    select.appendChild(el);
}
}

I don't know why it doesn't work but I rewrote it because it's the same result

aelgoa
  • 1,193
  • 1
  • 8
  • 24