1

I need to hide a text input field with javascript. Changing its type attribute to hidden does not work in IE (security issue).

What would be the best way to do it?

Note: No jQuery or other lib can be assumed.

4 Answers 4

1

I assume you have to show and hide the text field dynamically based on changing conditions in the form, otherwise you'd just make it an <input type="hidden"... to begin with.

Keep your code that shows and hides the field as it is, but also catch the onsubmit event.

In the submit handler, get your text field via document.getElementById(...) (or by accessing document.forms[i]) and check to see whether or not it's hidden.

If it is hidden, create a new DOM node for an <input type="hidden" ...> field and add that node to the form, probably via myform.appendChild(...). You'll have to give it the name your server-side code expects. Copy the contents of the hidden text field into the newly created type=hidden field, then return from your submit handler, allowing the standard submit to continue.

You could also just un-hide the text field on submit, but you'd have to move it "off screen" also or the user would see it reappear during submit processing.

Sign up to request clarification or add additional context in comments.

Comments

0

Try wrapping it in a div or span and then setting the display style to none when you want to hide it, and then to block (if you used a div) or inline (if you used a span) when you want to show it.

1 Comment

I need the value to be sent in form submission. As far as I know hidden items are not being sent by all browsers (except for input type='hidden')
0

document.myform.myelement.style.display = 'none'

works as expected even in Internet Explorer.

1 Comment

then the value is not submitted as part of form submission
0

The only way you can change it is before you append it to the DOM. You can make a new element and then replace the current one with it.

Look at replaceChild and createElement since you want to do manual DOM scripting. I assume you know what to do.

EDIT: "Hidden" fields as far as I know are sent. Have you checked whether they are? And you can also just do position:absolute; left:-9999em; to offset them.

1 Comment

Re position:absolute - yes, but then it remains in the tab order. If you also disable it that will prevent tabbing, but will it still get sent on submit?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.