Cannot pass getElementByID object to external JS file on Chrome

I've created a simple JS file, called formValueOperator.js, containing this function:

function setValue(type, obj, value){
if(type == 'text')
{
    obj.value = value;
}

and another HTML page calling this function:

<HTML>
   <HEAD>
      <title>Simple Test</title>
      <script type="text/javascript" src="formValueOperator.js"></script>
      <script type="text/javascript">
         function setInitValue(){
              var element_order_id = document.getElementById("order_id");
              setValue('text', element_order_id, 'aaa');
         }
      </script>
   </HEAD>
   <BODY>
         <FORM name="myform" method="post">
              <input type="text" size=20 id="order_id" name="order_id">
         </FORM>
         <script type="text/javascript">
              setInitValue();
         </script>
   </BODY>
</HTML>

It's quite a simple operation:

Run HTML --> call function setInitValue() --> put 'aaa' in text box.

Everything work perfectly on FireFox (7.0.1). However, when I tried to run this on Chrome (14.0.835.202), it didn't work at all.

Then, I tested the code by moving entire setValue function from formValueOperator.js and pasted it in HTML page. Surprisingly, it worked.

There must be something fishy about how Chrome pass getElementByID object to external JS file.

Could anyone please help me on this one?

Answers:

Answer

Try in this way, delaying the method execution until the web-pages has been loaded:

<FORM name="myform" method="post">
   <input type="text" size=20 id="order_id" name="order_id" />
</FORM>

<script type="text/javascript">
   window.onload = function() {
      setInitValue();
  };
</script>
Answer

It's to do with when the setInitValue() method is fired.

When you move your method outside of the JS file and into the body of the document you're probably delaying the executing of the method a few milliseconds giving the element you're selecting time to load.

Use jQuery's ready event to execute your code when everything has finished loading.

$(document).ready(function(){
  setInitValue();
 }
);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.