javascript - How to abstract this single case (showing text field based on selection of a drop down list) into a general function in jQuery? -
this first detailed question on so.
hi, have form , have many instances want show text field after drop down list when user selects "other" option in drop down list.
i using standard naming convention , wondering, have have many functions ddl/text field pairs in document, or can have single function can call on class of ddls? here's 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 jquery/javascript:
$(document).ready(function(){ $("#spotter").change(function () { //alert("you changed value of #spotter drop down menu."); if ($(this).val() == "other" ) //alert("you changed value of #spotter drop down menu 'other.'"); $("#spotter_other_div").css("visibility", "visible"); else $("#spotter_other_div").css("visibility", "collapse"); }); });
the initial state of div containing text field "collapse" in css.
i learning jquery , i'm @ point know how general case, , i'd see if function can write, or if have explicitly.
note page work in progress suggestions welcome (e.g. use span instead of div contain text field, etc.
thanks!
i see 2 options here.
- create function , parametrize out. sethen maleno's answer shows.
- make function more general function.
for example:
$(document).ready(function(){ // apply every select element $("select").change(function () { // dynamically build selector show/hide var secondmenuid = '#' + $(this).attr(id) + '_other_div' if ($(this).val() == "other" ) $(secondmenuid).css("visibility", "visible"); else $(secondmenuid).css("visibility", "collapse"); }); });
note approach requires discipline when generate html, , ids assigned appropriately (which seem doing since mention using standard naming convention).
this approach has advantage code have, , wouldn't need write lots of handlers.
sethen's gives little more flexibility in ids wouldn't need follow strict conventions (you pass whatever wanted arguments), require write function call attach every item want.
both techniques valid , have time , place.
Comments
Post a Comment