Topic: basic javascript toggle without making an ajax server call

I've been struggling with that for several days and I could not find a simple tutorial that explains what I want to do.
I need to do  javascript toggle:
if a check box is checked then show a div, if it is unchecked then hide the div.
I don't want an ajax call for that, because there is no need for a server action, this can slow down the page display to the user, and I'm just questionning whether there is a simple  javascript solution to perform such a simple action.
Ideally I'd like to use an :onselect option directly in the checkbox tag, something that would look like:
<%= check_box_tag(ingredient.id, "1", false,  :onselect => 'function() { ... }'  ) %> 
<div id="quantity" style="display:none"> ... </div>
Could you please help with the syntax of this, and/or point me to a tutorial.

Thanks

Re: basic javascript toggle without making an ajax server call

In your application.js file, add the following (jQuery).

$(document).ready(function(){
  // Hide the div that should be hidden. This line can be removed if you've hidden the div with CSS
   $("#the_div").css("display","none");

  // Add onclick handler to checkbox w/id checkme
   $("#your_checkbox").click(function(){

      // If checked
      if ($("#your_checkbbox").is(":checked")){
        // Show it
        $("#the_div").show("fast");
      }
      else{
        // Hide it
        $("#the_div").hide("fast");
      }
    });
});

It's that simple

Last edited by wesf90 (2012-07-20 23:06:02)

Remember to edit your topic title and add "[SOLVED]" if your question has been answered!

Follow me!

Re: basic javascript toggle without making an ajax server call

Thanks I will try that.