Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 9th, 2012  |  syntax: None  |  size: 1.37 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. <h1>Solution 01</h1>
  2. <p>Dropdown to show or hide a field</p>
  3.  
  4. <p>
  5.   <!--
  6.   * select tag with 'show' and 'hide' options
  7.   * "this" is the dropdown that user changed
  8.   * onchange event will trigger the javascript function
  9.    -->
  10.   <%= select_tag "demo_dropdown", options_for_select( ["hide", "show"]), :onchange => "showHideField( this);" %>
  11.   <!--
  12.   "display:none" hides the element when page is loaded
  13.   change this to "display:block" to show the element at page load
  14.    -->
  15.   <div id="dynamic_div" style="display:none;">
  16.     <%= text_field_tag "demo_field" %>
  17.   </div>
  18. </p>
  19.  
  20. <!-- javascript function that will be called onchange -->
  21. <script type="text/javascript" charset="utf-8">
  22.   //
  23.   // function name. accepts one argument in "dropdown" variable. actual object reference passed by 'this'
  24.   function showHideField( dropdown) {
  25.     //
  26.     // just some DRY code. otherwise we will have to repeat $('dynamic_div') instaed of "field"
  27.     field = $('dynamic_div');
  28.     //
  29.     // shorthand for the "if" conditional block in javascript
  30.     // ( condition ? expression_for_true_result : expression_for_false_result )
  31.     ( ( dropdown.value == 'show') ? field.show() : field.hide() )
  32.     //
  33.     // if conditional block below is exactly same as inline condition above
  34.     //
  35.     // if( dropdown.value == 'show') {
  36.     //   field.show();
  37.     // } else {
  38.     //   field.hide();
  39.     // }
  40.   }
  41. </script>