2

I have a rails view that displays a checkbox. When I click on the checkbox, a rjs function is called in my controller and it checks or unchecks the checkbox according to its previous state.

In the view :

<%= check_box_tag 'checkbox_test' %>

<%= observe_field 'checkbox_test',
  :url => { :action => :test_checkbox }
%>

In the controller :

def test_checkbox
  render :update do |page|
    page << "
      var checkBox = $('checkbox_test');
      checkBox.checked = !checkBox.checked;
    "
  end
end

The first time I click on the checkbox, everything works correctly, the function is called and the checked attribute is changed. The problem comes after: if I click again on the checkbox, the attribute doesn't change (but visually the checkbox changes...) and therefore the function "test_checkbox" is not called.

How can I solve this problem?

Jerem
  • 191
  • 1
  • 9

2 Answers2

2

Don't use the attribute at all. Just use the checked property. This is good advice for nearly every attribute and situation.

var checkBox = $('checkbox_test');
checkBox.checked = !checkBox.checked;
Tim Down
  • 318,141
  • 75
  • 454
  • 536
1

Seems to me you need $('checkbox_test')[0].checked to test checkedness.

checked property is a native DOM thing, not part of jQuery.

Jim
  • 521
  • 8
  • 14
  • I tried with `$('checkbox_test')[0].checked` and the behavior is the same as if I use `$('checkbox_test').checked` – Jerem Mar 05 '13 at 13:34