簡體   English   中英

嘗試使用ajax更新rails索引中的復選框值

[英]trying update checkbox value in a rails index with ajax

在Rails應用程序中單擊時,需要一些有關此Ajax代碼的幫助,以在復選框中更改index.html.erb中的布爾列。 我是javascript新手。

<% @budget_histories.each do |budget_history| %>
 <tr>
  <li class="checkbox m-b-15">
   <label>
    <input type="checkbox" onchange="checkAllBudgetHistoryItems(this, '<%= budget_history.id %>');" name="budget_history_items" id="budget_history_item_<%= budget_history.id %>" value="<%= budget_history.id %>" />
    <i class="input-helper"></i>
   </label>
  </li>
 </tr>
<% end %>
function checkAllBudgetHistoryItems(el, id) {
    if (el.checked) {
      $.ajax({
        type: 'PUT',
        url: '/budget_histories/update',
        data: 'budget_history_item_' + id,
        success: function (data) {
          $("#budget_history_items_tbody input").prop('checked', false);
        }
      });
    } else {
      $.ajax({
        type: 'PUT',
        url: '/budget_histories/update',
        data: 'budget_history_item_' + id,
        success: function (data) {
          $("#budget_history_items_tbody input").prop('checked', true);
        }
      });
    }
  }

單擊復選框時,如何使用ajax更新數據庫中的accept(boolean)屬性?

我已經解決了類似的問題:

  1. 創建一個控制器方法:
  def accept_budget    
    if @budget_history.toggle!(:accept)
      render json: {}, status: :ok
    else 
      render json: @budget_history.errors, status: :unprocessable_entity
    end
  end
  1. 建立路線
  resources :budget_histories do
    member do
      put :accept_budget
    end
  end
  1. 復選框html
<li class="checkbox m-b-15">
  <label>
    <input type="checkbox" onchange="checkAllBudgetHistoryItems(this, '<%= budget_history.id %>');" name="budget_history_items" id="budget_history_item_<%= budget_history.id %>" value="<%= budget_history.id %>" />
    <i class="input-helper"></i>
  </label>
</li>
  1. 編輯腳本:
<script language="javascript">
  function checkAllBudgetHistoryItems(el, id) {
    if (el.checked) {
      $.ajax({
        type: 'PUT',
        url: '/budget_histories/' + id + '/accept_budget',
        data: 'budget_history_item_' + id,
        success: function (data) {
          $(el).prop('checked', true);
        }
      });
    } else {
      $.ajax({
        type: 'PUT',
        url: '/budget_histories/' + id + '/accept_budget',
        data: 'budget_history_item_' + id,
        success: function (data) {
          $(el).prop('checked', false);
        }
      });
    }
  }
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM