Friday, February 11, 2011

How can I escape a DOM name in javascript?

I have a form element that I want to address via javascript, but it doesn't like the syntax.

<form name="mycache">
  <input type="hidden" name="cache[m][2]">

I want to be able to say:

document.mycache.cache[m][2]

but obviously I need to indicate that cache[m][2] is the whole name, and not an array reference to cache. Can it be done?

  • UPDATE: Actually, I was wrong, you can use [ or ] characters as part of a form elements id and/or name attribute.

    Here's some code that proves it:

    <html>
    <body>
    
    <form id="form1">
    
    <input type='test' id='field[m][2]' name='field[m][2]' value='Chris'/>
    
    <input type='button' value='Test' onclick='showtest();'/>
    
    <script type="text/javascript">
    function showtest() {
        var value = document.getElementById("field[m][2]").value;
        alert(value);
    }
    </script>
    
    </form>
    
    </body>
    </html>
    

    Update: You can also use the following to get the value from the form element:

    var value = document.forms.form1["field[m][2]"].value;
    
    DGM : That got me going the right direction.... being able to quote the name as a array index is nice.
    David Dorward : The name can include [ and ] characters, but the id may not (even if browsers perform error recovery).
  • Is it possible to add an id reference to the form element and use document.getElementById?

    From FlySwat
  • Use document.getElementsByName("input_name") instead. Cross platform too. Win.

    Chris Pietschmann : Actually getElementByName is not cross-platform. It's an IE specific thing.
    FlySwat : Actually it is, http://developer.mozilla.org/en/DOM/document.getElementsByName its just buggy from one browser to the next.
    Juan Mendes : Actually, :), name attribute is only valid for form elements in XHTML, that's why it's buggy! It works fine if you're only using it for input select and textareas
    From Oli
  • -- and in the old days (in HTML3.2/4.01 transitional/XHTML1.0 transitional DOM-binding) you could use:

    form.elements["cache[m][2]"]
    

    -- but the elements-stuff is, as Chris Pietschmann showed, not necessary as these binding-schemes also allow direct access (though I personally would prefer the extra readability !-)

    DGM : Well son of a gun. I thought I tried that but could only get numeric entries to work. But sure enough, it works.
    roenving : .elements and a lot other element-collections (.images, .frames and so on !-) are exactly collections, so elements is accessible in both ways ...
    From roenving

0 comments:

Post a Comment