remote checkbox helper

using check_box_tag with remote_function

...here's a Rails helper example of sending a checkbox click with Ajax.

  # call remote function by change event.
  # uses unobtrusive js instead of inline.
  # parameters:
  #   <tt>dom_id</tt> is element id for checkbox
  #   <tt>remote_options</tt> are options to remote_function
  #   <tt>value</tt> is same as core check_box helper
  #   <tt>checked</tt> is same as core check_box helper
  #   <tt>options</tt> is same as core check_box helper
  def check_box_tag_remote(dom_id, remote_options, value = '1', checked = false, options = {})
    html = ''
    
    options.merge!({:id => dom_id})
    html << check_box_tag(dom_id, value, checked, options)
    
    remote_options.merge!({:with => %("value=#{value}")})
    remote_js = remote_function(remote_options)
    
    html << javascript_tag(%Q{
      Event.observe('#{dom_id}', 'change', function(evt) {
        #{remote_js}
      }
      );
    })
  end

The controller action is butter-bread simple:


  def toggle_some_attr
    # params[:value] is available if needed

    model = SomeModel.find(params[:id])
    model.toggle!(:some_attr)
    
    render :nothing => true
  end

Simple enough. Notice the use of Event.observe from prototype.js for less-obtrusive js and the :with param added to remote_options, in case you need to pass an extra param to your controller (in this case params[:value]).

And finally, the view:


  <%= check_box_tag_remote "checkbox_#{@object.id}", 
    {
    :url => { :action => 'toggle_some_attr', :id => @object.id }, 
    :loading => "Element.show('spinner')",
    :complete => "Element.hide('spinner')"}
    },
    '1',
    @object.some_attr == '1' ? true : false
  %>

Posted by Luke on Monday, August 06, 2007