Link to home
Start Free TrialLog in
Avatar of glass_snake
glass_snake

asked on

Input field x,y co-ordinates when in a table

I'm working on a JavaScript that will determine the physical location of the input fields on a page.  My script works perfectly fine under most circumstances.  However, if the input field is located inside of a table, the script returns a really odd location for the field.  I've included a very simple page below that demonstrates what I'm talking about.

Does anyone have any insight on why it's doing this and how I can fix it?

====================================

<HTML>
   <HEAD>
      <title>JavascriptControlProblem</title>
   </HEAD>
   <body>
      <form id="Form1">
            <input type="text" id="fieldA"><br>
            <input type="text" id="fieldB"><br>

            <table>
               <tr><td><input type="text" id="field1"></td></tr>
               <tr><td><input type="text" id="field2"></td></tr>
               <tr><td><input type="text" id="field3"></td></tr>
               <tr><td><input type="text" id="field4"></td></tr>
               <tr><td><input type="text" id="field5"></td></tr>
            </table>
           
         <script language="javascript">
               var ctl;
               for(i=0; i<document.forms[0].elements.length; i++){
                  if (document.forms[0].elements[i].type == 'text') {
                     ctl = document.forms[0].elements[i];
                     alert(ctl.id + ' --- ' + ctl.offsetLeft + ', ' + ctl.offsetTop);
                  }
               }
         </script>
     
      </form>
     
   </body>
</HTML>
ASKER CERTIFIED SOLUTION
Avatar of Lakio
Lakio
Flag of Iceland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I think Lakio has the solution for your problem.

The EXPLANATION for your problem is that the offsets are from the PARENT element.  So if you run

     <script language="javascript">
      var ctl;
      for(i=0; i<document.forms[0].elements.length; i++){
            if (document.forms[0].elements[i].type == 'text') {
                  ctl = document.forms[0].elements[i];
                  alert(ctl.outerHTML+ ' --- ' + ctl.offsetLeft + ', ' + ctl.offsetTop);
                  var j = 1;
                  for (ctl = ctl.parentNode; ctl; ctl = ctl.parentNode) {
                        if (ctl == document.forms[0]) {
                              break;
                        }
                        alert(ctl.outerHTML + ' -' + j + ' - ' + ctl.offsetLeft + ', ' + ctl.offsetTop);
                        j++;
                  }
            }
      }
</script>

instead you will see how for any one element, the real position in the form is the sum of the positions going up toward the form.
Avatar of Zvonko
I knew that jensfiederer but Im to lasy so thanks :D