Topic: JavaScript show/hide div

I'm really new to Javascript and RoR, and have been trying to figure this out for hours with no avail... So basically, I want to implement user registration, with conditional. If user's status is "Student", the form for "Grade" should show and "Year" should be hidden. If user's status is "Alumni", the form for "Year" should show and "Grade should be hidden. Other than this show/hide, the form works out fine.

So far I have :
in new.html.erb

  <div class="field">
    <%= f.label :status, "Status" %><br />
    <%= f.select ("status", { "Student" => "Student",
                                    "Alumni" => "Alumni"}, 
                                    {:include_blank => ""},
                                    {:onchange => "showCustomField(this.value)" }) %>
  </div>                                
  
  
  <div id="grade_div" class="field" style="display:none;">
    <%= f.label :grade, "Grade" %><br />
    <%= f.select :grade, (10..12) %>
  </div>
  

  <div id="year_div" class="field" style="display:none;">
    <%= f.label :year, "Graduation year" %><br />
    <%= f.select :year, (2000..2010) %>
  </div>  

in custom_field.js:

<script language="javascript">

function showCustomField(choice)
{
  if (choice == "Student"){
    document.getElementById("grade_div").style.display = 'block'      
    document.getElementById("year_div").style.display = 'none'            
  } else if (choice == "Alumni"){
    document.getElementById("year_div").style.display = 'block'        
    document.getElementById("grade_div").style.display = 'none'      
  }
}
</script>

and in header I've included     <%= javascript_include_tag 'custom_field' %>

I'll really appreciate your help! thanks!

Last edited by macca (2010-12-16 02:57:55)

Re: JavaScript show/hide div

Are you any JS libraries?

Re: JavaScript show/hide div

Yes,  ya have use the JavaScript Helpers and JQuery or Prototype to be efficient with JavaScript and Rails.

Your JavaScript, using JQuery, would look like

if (choice == "Student") {
    $("#grade_div").show();
    $("#year_div").hide();           
} else if (choice == "Alumni") {
    $("#grade_div").hide();
    $("#year_div").show();           
}

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: JavaScript show/hide div

I got it to work! apparently I shouldn't have <script language="javascript"> </script> in the *.js file.... thanks a lot for the help!