Rails Check_Box_Tag How to Pass Value When Checked Ajaxily

Rails check_box_tag how to pass value when checked ajaxily

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 }
});
});

Rails check_box_tag checked according boolean value

The proper use of the check_box_tag method is like this:

= check_box_tag :name, value, checked

Where value can be anything, checked (should be) a boolean.

In your case:

= check_box_tag :is_in_city, 1, c.is_in_city

Documentation here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-check_box_tag

check_box_tag is not accepting values

All the checkboxes are displayed as checked because you are passing option 0 as checked to the check_box_tag and ruby interprets 0 as a true value.

<td><%= check_box_tag(task.erledigt, 1, 0) %> </td>

Simply, update the above as

<td><%= check_box_tag("task_erledigt",task.erledigt, task.erledigt == 1 ? true: false ) %> </td>

So, based on the value of task.erledigt the checkbox would display checked or unchecked state.

Archiving entries with checkbox and haml

your issue looks similar to this solution. you can try that, and post if you want any different from it.

How to add a boolean toogle to a Rails index view?

The way we do this is to add an observer to the checkbox and send a request to the update action or add a new action just for this feature. The advantage of adding a new action is it's concentrated on that particular feature, no additional checks and stuff.

You will be changing/adding a few files so here it goes. Hopefully they are easy to understand.

# view
<td><%= check_box_tag :approved, user.id, user.approved?, class: 'user-approve-cb' %>

# routes
resources :users do
put :set_approved, on: :member
end

# js asset (using coffee)
$('.user-approve-cb:checkbox').change ->
$.ajax
url: '/users/' + @value + '/set_approved'
type: 'PUT'
data: { approved: $(this).attr('checked') }
success: -> alert('User updated')

# controller
def set_approved
@user = User.find params[:id]
@user.update_column :approved, params[:approved]

render nothing: true
end


Related Topics



Leave a reply



Submit