Rails check_box_tag how to pass value when checked ajaxily

后端 未结 4 1800
死守一世寂寞
死守一世寂寞 2021-01-01 03:58

On my index page for my Task model, I want to show a checkbox for every row that corresponds to the boolean field \"complete\" in my Task database table.

Currently m

相关标签:
4条回答
  • 2021-01-01 04:36

    The suggestion from this issue in rails/jquery-ujs github repo worked for me: https://github.com/rails/jquery-ujs/issues/440#issuecomment-197029277

    For you it would be:

    <%= check_box_tag 'complete', '1', task.complete, {
      onchange: "$(this).data('params', 'complete=' + this.checked)",
      data: { url: url_for(action: 'complete', id: task.id,), remote: true, method: :patch },
    } %>
    
    0 讨论(0)
  • 2021-01-01 04:38
    check_box_tag 'complete', task.complete ? 'false' : 'true', task.complete, ...
    :url => url_for( :action => 'complete', :id => task.id )
    

    This way in your controller you can get params[:complete]. And you should implement complete.js.erb to rerender checkbox, so next click will send inverse value

    Or you can implement js on click event

    $('.input-large').on('click', function() {
      $.ajax({
        type: "PUT",
        url: "/tasks/complete/" + $(this).data('post-id')
        data: { complete: $(this).is(':checked') }
      });
    });
    

    and don't forget to place data-post-id param to your checkbox

    0 讨论(0)
  • 2021-01-01 04:39

    As of Rails 4, you should be able to ditch all the JS from the original answer. The code in your question should just work due to jQuery UJS magic.

    It turns out that adding remote: true to an input causes jquery-ujs to make it ajax-y in all the nice ways. Thoughtbot's "A Tour of Rails jQuery UJS" briefly touches this (and many other good things available); the "Unobtrusive scripting support for jQuery" page in the jQuery UJS wiki does a thorough job on this as well.

    0 讨论(0)
  • 2021-01-01 04:50

    If you are using jQuery, you can write a click event.

    $('.input-large').click(function() {
      var checked; 
      if ($(this).is(':checked')) {
        checked = true;
      } else {
        checked = false;
      } 
      $.ajax({
          type: "POST",
          url: "/tasks/complete",
          data: { id: $(this).data('post-id'), checked: checked }
       });     
    });
    
    0 讨论(0)
提交回复
热议问题