Unchecking a box becomes impossible in Rails and Ajax due to boolean constraints

Even though I've come across several similar questions, I'm still struggling to make mine work correctly. Here's what my code looks like...

#app/views/tasks/index.html.erb
<%- @tasks.each do |task| %>
  <div class="task-wrapper">
    <%= check_box_tag 'checked_in', task.id , task.checked_in, :class => "task-check" %>
    <%= content_tag :span, task.name %>
  </div>
<% end %>
<%= link_to 'New Task', new_task_path %>

  <script>
$(".task-check").bind('change', function(){
  if (this.checked){
    $.ajax({
      url: '/tasks/'+this.value+'/toggle',
      type: 'POST',
      data: {"checked_in": this.checked}
    });
  }
  else {
     alert("no");
  }
});
  </script>

#app/controllers/tasks_controller.rb
...
def toggle
  @task = Task.find(params[:id])

  if @task.update_attributes(:checked_in => params[:checked_in])
    # do I need something here?
  else
    # do I need something here?
  end
end
...

In my task model, I have a 'checked_in' attribute that is boolean.

The source of this code was inspired by the following question...

Rails change boolean value with checkbox and jquery ajax

...and although I took reference from it, I am still unsure about some parts. While creating a new task, I can successfully mark the box checked to set my boolean value as true. However, when I uncheck the box, I receive a JavaScript pop-up saying "No", but nothing gets updated in the database and no information is sent back to the server.

Can anyone provide any insights or solutions?

Answer №1

Your issue stems from the JavaScript code you have written.

$(".task-check").bind('change', function(){
  if (this.checked){
    $.ajax({
      url: '/tasks/'+this.value+'/toggle',
      type: 'POST',
      data: {"checked_in": this.checked}
    });
  } 
  else {
    alert("no");
  }  
});

When you check or uncheck the box, the change event is triggered. The code then tests for this.checked. If it returns false, which happens when the box is unchecked, the condition is not met and the script goes directly to the else statement, triggering the alert function.

To resolve this issue, consider removing the conditional statement entirely.

Answer №2

That's the mechanism behind how browsers operate - they only transmit data for checked checkboxes.

The status of checking/unchecking is contingent upon whether the parameter is present or not.

Answer №3

Thank you, Antoine. It worked perfectly. I am really trying my best to grasp JS. For future reference, here is the solution that worked for me...

app/views/tasks/index.html.erb

<%- @tasks.each do |task| %>
  <div class="task-wrapper">
    <%= check_box_tag 'checked_in', task.id , task.checked_in, :class => "task-check" %>
    <%= content_tag :span, task.name %>
  </div>
<% end %>
<%= link_to 'New Task', new_task_path %>

  <script>
$(".task-check").bind('change', function(){
    $.ajax({
      url: '/tasks/'+this.value+'/toggle',
      type: 'POST',
      data: {"checked_in": this.checked}
    });
});
  </script>

In addition, I encountered a template error in the console, so here is the updated controller code.

  def toggle
    @task = Task.find(params[:id])
    @task.update_attributes(:checked_in => params[:checked_in])
    render :nothing => true
  end

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ignore missing values when performing an upsert operation

I'm currently utilizing pg-promise to manage my Postgres queries, but I've hit a roadblock with the following query conundrum: My goal is to develop a single method that can batch upsert multiple rows simultaneously. Here's the code snippet ...

Updating information without the need for a page refresh

My project involves text boxes and drop-down menus where users input data, then click "generate" to combine the text from the boxes and display the result on the page. I'm struggling with clearing these results if the user clicks generate again, for ...

What is the best way to execute a PHP function using AJAX?

I have my server running on localhost using XAMPP. I am trying to trigger a JavaScript function that will send some data from the browser to a PHP script. The JavaScript function is supposed to be executed when a button on my HTML page is clicked: functi ...

Issue with ReactJS on the server side rendering

Could someone please help me understand my current issue? On the server side (using Node.js), I have the following code: var React = require('react'); var ReactDOMServer = require('react-dom/server'); var TestComponent = React.create ...

Text randomly appears on the html page

I've been dedicating a significant amount of time to finding a solution, but haven't had any luck. I'm aiming to create a visual effect where 10 words with varying font sizes slide in from different directions on a canvas within my document ...

Utilizing Vue.js to set the instance global property as the default value for a component prop

Is it possible to access a global property from my vue instance when setting a default prop value in my component? This is what I would like to achieve props: { id: { type: String, default: this.$utils.uuid } } I attempted to use an arrow fun ...

Step-by-step guide on implementing a border-bottom for an active link

Is there a way to apply a border-bottom to btn_articles and btn_posts when one of them is clicked? I attempted to use the active class but it did not have the desired effect. Any suggestions or solutions would be greatly appreciated. let btn_articles = ...

Utilize jQuery to swiftly align elements within a designated container

Check out my JSFiddle example: http://jsfiddle.net/c62rsff3/ I'm attempting to implement snapping behavior between 2 elements using this code: $('.draggable-elements').draggable({ snap: true }); In addition, I've defined a container ...

How to manage multiple items within a single MUI/React TextField

Recently diving into the world of JS, React, and MUI, I find myself faced with a challenge involving a MUI TextField that is supposed to handle multiple values. For example: 1*10 5*50 13*250 5*50 1*10 3*33.33 4*25 3*33.33 All on a single line. These ...

The validation for decimal numbers fails to function when considering the length

I've been struggling to come up with a regular expression for validating decimal numbers of a specific length. So far, I've tried using pattern="[0-9]){1,2}(\.){1}([0-9]){2}", but this only works for numbers like 12.12. What I'm aimin ...

Can a variable declared in wdio.conf be accessed?

Within the wdio.conf file, I have implemented a function called onPrepare where I am storing all my feature files in an array. let listOfFiles = fs.readdirSync(process.cwd() + '/features'); var featureFiles = []; listOfFiles.map((file) => { ...

When sharing a Laravel AJAX request, it does not include any arguments

I'm encountering difficulties passing arguments through a Laravel AJAX request. Despite numerous similar inquiries, none seem to offer a solution tailored to my specific issue. Below are my Laravel routes: Route::get('workerAjax', function ...

Extracting a data element from a JSON array nested within an object

I am attempting to retrieve a value from a JSONP web-service, however I am unsure of the method to access this specific value within the JSON array. $('#bookThumbnaill').attr('src', bookDetails.volumeInfo.imageLinks.thumbnail); $(&apo ...

Is there a way to prevent my timer from resetting whenever I refresh the page?

Hey everyone, I'm new to coding and I could really use some help here. I have this code for a timer but I'm struggling to make it work properly even after refreshing the page. My goal is to keep the timer running smoothly, but I'm not sure w ...

Having trouble loading the Javascript file after redirection?

After a redirect in my ASP.NET Core web app, I noticed that my custom JavaScript file does not get loaded. It is included at the bottom of the _layout.cshtml page. <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/j ...

How can I prevent SweetAlert from automatically focusing when it first opens?

I recently integrated SweetAlert into my project and customized the buttons like this: swal("A wild Pikachu appeared! What do you want to do?", { buttons: { cancel: "Run away!", catch: { text: "Throw Pokéball!", value: "catch", ...

What is the simplest method for comparing transaction amounts?

I'm in the process of integrating PayPal into my website using their REST API. My goal is to allow users to input the amount they want to deposit. While I can obtain the total during payment creation, I'm unsure how to smoothly pass it to the exe ...

Encountering issues with loading Angular formControl

I've been going through an Angular tutorial on forms, which you can check out here. In my 'datasources.component.html' file, I have the following code: <form [formGroup]="queryForm"> <label>Query: <input type="text" formCont ...

Generating an image in Fabric.js on a Node server following the retrieval of canvas data from a JSON

I've been trying to solve this problem for the past few days. In my app, users can upload two images, with one overlaying the other. Once they position the images and click a button, the canvas is converted to JSON format and sent to a node (express) ...