Search code examples
javascriptfirefoxgoogle-apps-scriptappendchildgoogle-caja

Google Caja appendChild not updating form.elements in Firefox


I'm using a Google Apps Script Web App and HtmlService to serve the content and I'm trying to dynamically add input elements to a form with appendChild. It works in Chrome 24 and IE 10, but Firefox 19.0.2 doesn't update the elements listing for the form.

So, it displays correctly on the webpage, but in Firefox, any input elements added with appendChild to the form aren't part of the form.elements collection. It's worth noting this issue only appears when the HTML is sanitized with Caja, if I use the same code in jsfiddle it works fine.

The issue can be seen here, which is just the following code:

<html>
      <head>
        <title>Test</title>
        <script type="text/javascript">
          function print(form)
          {
            var str = "";
            for(var v = 0; v < form.length; v++)
            {
              str += "<br>" + form[v].nodeName + "." + form[v].id + ": ";
              if(form[v].elements != undefined)
                for(var w = 0; w < form[v].elements.length; w++)
                {   
                  str += form[v].elements[w].name + ", ";
                }
            }
            return str;
          }

          function submitForm()
          {        
            document.getElementById("nameLookupHelp").innerHTML = (print(document.forms)) + "<br>Total Elements:" + document.forms[0].elements.length;
            return;
          }

          function onLoad()
          {
            var name = document.getElementById("nameForm");
            var t = document.createElement("input");
            t.name = "TestInput";
            //t.id = "TestInput";
            name.appendChild(t);
          }
        </script>
      </head>
      <body onload="onLoad()">
        <form name="nameForm" id="nameForm">
          <input name="nameLookup" id="nameLookup">
          <input type="button" id="bntNameForm" onclick="submitForm(this)" value="Lookup">
          <div class="" id="nameLookupHelp">Please enter your name.</div>
        </form>
      </body>
    </html>

From what I've found on the subject, Firefox doesn't like invalid HTML; however, from what I can tell, the HTML output is perfectly valid. More over, since it works on jsfiddle, I assume the issue has to be with the way Caja is interacting with my HTML and Firefox.

Also, one last thing, if I inspect the form element in Firefox and double click on the form tag in the markup panel, then click off (cancel editing), Firefox then detects all of the elements and everything works fine. What Firefox displays as the HTML doesn't change though.

Thank you in advanced for your help.


Solution

  • Congratulations, you found a bug; a form's .elements never updates after the first time it is accessed. I have fixed it in Caja r5321.