Garry
Garry

Reputation: 4533

How to get an html element from document.form

I have a situation where I need to get the element in JavaScript from document.form.elementname but the problem is that, my element name contains '.' periods in it.

So in actual its like document.form.my.stack.element where "my.stack.element" is the name of element. Changing the name is not in my hands and cannot be done so getElementById is the only solution left?

Please let me know if I can still get the element using its name from the form?

Upvotes: 0

Views: 95

Answers (3)

Works On Mine
Works On Mine

Reputation: 1121

One thing that you can use is the square bracket notation to access the properties of an object.

So you could use

document.form["my.stack.element"];

Upvotes: 1

KarelG
KarelG

Reputation: 5234

you can access form names by using it as an associative array. The .name is just an alternative to the associative array key example.

document.form.my.stack.element 

is same as

document.form['my.stack.element']

Please note that the first snippet is an example. Of course it doesn't work because the js would treat is as an array, threatening it as document.form['my']['stack']['element'] due of punctuations.

Upvotes: -1

Minko Gechev
Minko Gechev

Reputation: 25682

Use: document.form['my.stack.element'].

HTML

<form name="form">
  <input name="my.stack.element">
</form>

Upvotes: 2

Related Questions