How to hide an HTML input field with javascript
I need to hide a text input field with javascript. Changing its type attribute to hidden does not w开发者_StackOverflowork in IE (security issue).
What would be the best way to do it?
Note: No jQuery or other lib can be assumed.
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.
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.
document.myform.myelement.style.display = 'none'
works as expected even in Internet Explorer.
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.
精彩评论