I have a form, like so:
<form action="" method="post">
<select name="pageType">
<option value="main">Main Page</option>
<option value="sub">Sub Page</option>
<option value="sub-sub">Sub-Sub Page</option>
</select>
<br />
<label>Choose Sub Sub Name:</label> <input type="text" name="sub-sub-name" />
<br />
<input type="submit" name="submit" value="GO!" />
</form>
What I would like to achive is for this text field (and it’s label):
<label>Choose Sub Sub Name:</label> <input type="text" name="sub-sub-name" />
to only appear if the 3rd option (sub sub page) is selected from the drop down and not show up otherwise. How can this be done with either javascript or the jquery framework?
EDIT
by the way, it would be nice if this can be achieved without the page needing to refresh and losing previously submitted form data. I know form data can still be kept using variables that store the values even on page refresh, but I was hoping for that effect that I see on a lot of sites where the additional text area (or other form element) just appears without page refresh.
Hiding/showing the label and the field is easy. Put the field in the label (which associates them), give the label
style="display: none", and give it an ID. E.g.:Then you can show it via
show…and hide it via
hide:…or (and it’s not hyper-clear from the docs, but if you get to the bottom of the page you’ll find it) you can toggle based on a boolean value using
toggle:So now what you need is a trigger that fires when the third option in the select is chosen. There’s the
changeevent, but it doesn’t fire until the focus leaves the select field. (jQuery normalizes that; otherwise, when it fired would be browser-dependent.) You could tryclickon the option itself, but I don’t know if it’s reliable when navigation is via the keyboard.To be proactive (which is particularly important if the field you’re showing immediately follows the select box in the tab order!), I tend to use a timer to watch for changes (an idea I got from the Prototype guys, they have a whole class for this):
(There I assume you’ve given the id
mySelectFieldto your select field.) When you don’t need to do this anymore, you want to cancel the interval:Naturally you wouldn’t do all of the above at the top level, that would itnroduce a bunch of global variables. You’d put it inside a scoping function.