Tuesday, April 25, 2017

Display a TextBox only when a Radio Button is Checked

I was working on one of my websites this week, and needed the ability to allow the user to input some text only when a certain radio button is checked, and make the TextBox go away when another radio button is checked. All the TextBox's are hidden on page load, then activated when the "Other" radio button is checked. I also use placeholder="" to give the user some idea of what goes into the box.  After a few tries, I got it working and figured, if I needed this, others may as well, and to save you some time and angst, here is my code. Works well in HTML or PHP (just add echo' ... '; pieces).

Enjoy!

Code:
https://pastebin.com/LA9YxXQh

2 comments:

  1. Hey Steve,

    I put together this example that shows how you could accomplish the same thing using css and should help simplify the process for you.

    https://codepen.io/cedmond/pen/qmrpma?editors=1100#

    Using this method you wouldn't have to define every field in your javascript function in order to make it work. The display of the field is handled by the :checked state of the radio button, which then displays the next input in the HTML structure.

    Hope you find this useful,
    Craig
    craig@cedmond.com

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...