Friday, 9 August 2013

How to abstract this single case (showing text field based on selection of a drop down list) into a general function in jQuery?

How to abstract this single case (showing text field based on selection of
a drop down list) into a general function in jQuery?

This is my first detailed question on SO.
Hi, so I have a form and have many instances where I want to show a text
field after a drop down list when the user selects the "Other" option in
the drop down list.
I am using a standard naming convention and am wondering, do I have to
have as many functions as DDL/text field pairs in the document, or can I
have a single function I can call on a class of DDLs? Here's the HTML:
<label for="spotter">Spotter:</label>
<select id="spotter" required>
<option value="Snoop Dogg">Snoop Dogg</option>
<option value="MC Escher">MC Escher</option>
<option value="Linus Thorvalds">Linus Thorvalds</option>
<option value="Other">Other</option>
</select>
<br/>
<div id="spotter_other_div"><label for="spotter_other">Other
Spotter:</label><br><input type="text" name="spotter_other"
id="spotter_other" size="50" required/></div>
and here's the jQuery/javascript:
$(document).ready(function(){
$("#spotter").change(function () {
//alert("You just changed the value of the #spotter drop down
menu.");
if ($(this).val() == "Other" )
//alert("You just changed the value of the #spotter drop down
menu to 'Other.'");
$("#spotter_other_div").css("visibility", "visible");
else
$("#spotter_other_div").css("visibility", "collapse");
});
});
The initial state of the div containing the text field is "collapse" in css.
I am learning jQuery and I'm at the point where I know how to do something
for a general case, and I'd like to see if this is a function I can write,
or if I have to do it explicitly.
Note that the page is a work in progress so any suggestions are welcome
(e.g. use a span instead of a div to contain the text field, etc.
Thanks!

No comments:

Post a Comment