简体   繁体   中英

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 work 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.

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; position:absolute; left:-9999em; to offset them.

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

works as expected even in Internet Explorer.

尝试将其包装在div或span中,然后在要隐藏它时将显示样式设置为none,然后在想要显示时将其阻塞(如果使用div)或嵌入式(如果使用span)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM