在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)属性?
答案 0 :(得分:0)
我已经解决了类似的问题:
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>