最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to hide an HTML input field with javascript - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Nov 23, 2010 at 16:07 NirNir 25.4k26 gold badges84 silver badges120 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 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.

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.

发布评论

评论列表(0)

  1. 暂无评论