[英]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)屬性?
我已經解決了類似的問題:
def accept_budget
if @budget_history.toggle!(:accept)
render json: {}, status: :ok
else
render json: @budget_history.errors, status: :unprocessable_entity
end
end
resources :budget_histories do
member do
put :accept_budget
end
end
<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>
<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.