0

Please help take a look at the following code, its working when calling function displayResult() with button onclick. but I want it to be automatically run when open the page....I've tried but still not working....Thanks

<form>
<select id="mySelect">
  <option>SELECT</option> 
</select>
</form>



<script language="JavaScript" type="text/javascript">
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","xmltag.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML; 
x2=xmlDoc.getElementsByTagName("CONTROL_POINT");   

 function displayResult()
{
for (i=0;i<x2.length;i++)
  {  
var x=document.getElementById("mySelect");
var option=document.createElement("option"); 
option.text=x2[i].childNodes[0].nodeValue;
try
  {
  // for IE earlier than version 8
  x.add(option,x.options[null]);
  }
catch (e)
  {
  x.add(option,null);
  } 
  } 
} 
</script>
1
  • Instead of try..catch, you can use the DOM 0 method of adding options: var opt = new Option(text, value) which works in every browser back to the beginning. Then just append it it to the select: x.options[x.options.length] = opt; or similar. Commented Dec 22, 2011 at 3:57

1 Answer 1

1

You need to call displayResult() after the elements it manipulates have been parsed. So add the following code to a script block at the bottom of your page source (or in an onload or document.ready event handler):

displayResult();
Sign up to request clarification or add additional context in comments.

4 Comments

I've put $(window).load(function() { displayResult(); }); at the bottom of scripts but it still not working =(
You can almost certainly use $(document).ready(function(){ displayResult(); }); rather than $(window).load();. But if you're putting it at the bottom of the page you should be able to just put displayResult();.
P.S. I forgot to mention this in my answer, but you seem to be doing a synchronous ajax request. If you switch that to asynchronous ajax you could probably populate your select element directly in the ajax success callback. Either way, from your comment above it seems you are using jQuery, so why don't you use the jQuery ajax functions? If you're using a library anyway why do all the cross-browser stuff yourself?
good idea! in this case i could read xml file from my backend and return this whole thing back to html! thanks so much for the advice!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.