"Utilizing Rails 3 to initiate an AJAX submit when radio buttons are changed leads to the generation of

Need help with Rails 3 form partial

<%= form_for(answer, :remote => true) do |f| %>
  <% if answer.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(answer.errors.count, "error") %> prevented this answer from being saved:</h2>
      <ul>
        <% answer.errors.full_messages.each do |msg| %>
            <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
  <div class="field">
    <%= f.hidden_field :conduct_evaluation_id, :value => conduct_evaluation.id %>
  </div>
  <div class="field">
      <%= f.hidden_field :question_id, :value => question.id %>
  </div>
  <div class="field">
    <%= f.hidden_field :program_block_id, :value => conduct_evaluation.program_block_id %>
  </div>
  <div class="field">
    <%= f.radio_button :answer, true, :onchange => "$(this.form).trigger('submit.rails');" %>yes<br/>
    <%= f.radio_button :answer, false, :onchange => "$(this.form).trigger('submit.rails');" %>no<br/>
  </div>
  <div class="actions">
    <%= f.submit "Answer" %>
  </div>
<% end %>

Issues with controller actions:

  # POST /answers
  # POST /answers.json
  def create
    @answer = Answer.new(params[:answer])
    @answer.user = current_user
    @answer.conduct_evaluation = ConductEvaluation.find(params[:answer][:conduct_evaluation_id])

    respond_to do |format|
      if @answer.save
        format.js { }
        format.html { redirect_to @answer, notice: 'Answer was successfully created.' }
        format.json { render json: @answer, status: :created, location: @answer }
      else
        format.js { }
        format.html { render action: "new" }
        format.json { render json: @answer.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /answers/1
  # PUT /answers/1.json
  def update
    @answer = Answer.find(params[:id])

    respond_to do |format|
      if @answer.update_attributes(params[:answer])
        format.js { }
        format.html { redirect_to @answer, notice: 'Answer was successfully updated.' }
        format.json { head :no_content }
      else
        format.js { }
        format.html { render action: "edit" }
        format.json { render json: @answer.errors, status: :unprocessable_entity }
      end
    end
  end

Seeking JavaScript help for AJAX submission issue. The request is HTML instead of JS when using onchange event for radio button submit. Any input appreciated!

-J

Workaround discovered: Bind change event for radio buttons to clicking the submit button. Not ideal but functional.

CoffeeScript solution: $(document).ready -> $('#my_form input:submit').hide() $('#my_form input:radio').change -> $.ajax type: $(this.form).attr('method') url: $(this.form).attr('action') data: $(this.form).serialize() dataType: 'script' This allows the corresponding js action file to be automatically executed on success.

Answer №1

To avoid triggering Rails magic and prevent the form from submitting automatically, use a custom change method like this:

$('input.checkbox_selector').change( function() { 
    $.ajax({
        url: $('#custom_form').attr('action'), 
        data: $('#custom_form').serialize() 
    }); 
});

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

Utilizing external clicks with Lit-Elements in your project

Currently, I am working on developing a custom dropdown web component using LitElements. In the process of implementing a feature that closes the dropdown when clicking outside of it, I have encountered some unexpected behavior that is hindering my progres ...

What is the best way to toggle between rendering two components or updating two outlets based on a route in React Router?

There is a React application I am working on that utilizes React-Router. My layout component has the following structure: import React from 'react'; import Header from './components/Header/Header'; import Footer from './components/ ...

What is the best way to transform an object into serialized data syntax for use in the jquery.ajax function?

When using my jQuery.ajax function, I am struggling to find a way to convert my object into the serialized format required for sending. $.ajax({ type: 'post', url: 'www.example.com', data: MyObject, success: function(data) { ...

A bot responsible for assigning roles never fails to remove a role when necessary

My goal was to develop a bot that automatically assigns users a role based on the language they speak in a bilingual server. However, when I tried to assign myself the Czech role, it added the role but failed to remove the rest: const Discord = require(&a ...

Point the API endpoint to a different file

Is there a method to proxy a specific binary file, such as redirecting a PDF file to another PDF file using something like app.use('/proxy', proxy('/desiredPath'))? I have tried this approach, but it does not seem to work for the parti ...

Preventing Content Changes When Ajax Request Fails: Tips for Error Checking

I was struggling to find the right words for my question -- My issue involves a basic ajax request triggered by a checkbox that sends data to a database. I want to prevent the checkbox from changing if the ajax request fails. Currently, when the request ...

Leveraging Vue.js to preload data with client-side rendering

When it comes to server-side rendering in Vue, like with Nuxt, the process involves grabbing data using the serverPrefetch() function and rendering content on the server side. This allows for the request to return data to the user only after the initial do ...

Please be patient for the PayPal script to load on the nextjs page

I've encountered an issue with my code that is meant to display PayPal buttons <Head> <script src="https://www.paypal.com/sdk/js?client-id=KEY"></script> </Head> The PayPal buttons are loaded within the ...

Determine whether a given string is a valid URL and contains content

Is there a way to ensure that one of the input fields is not empty and that the #urlink follows the format of a URL before executing this function in JavaScript? $scope.favUrls.$add I'm uncertain about how to approach this. html <input type="te ...

The VueRouter is unresponsive and not functioning as expected

I have been delving into Vue. Through the npm install vue-router command, I added vue-router to my project. Subsequently, I incorporated VueRouter and defined my URL paths within the VueRouter instances located in the main.js file. I created an About compo ...

Modal containing Jquery GalleryView

I am facing an issue with loading galleryView inside a modal. Even though using galleryView on its own works fine, I have been unable to make it work within a modal. Despite looking for solutions in previous posts, I couldn't find anything that fixed ...

Issues with Javascript Arrays not adding objects with duplicate values

When objects have arrays with the same values, only one of them is considered. For example: data[2018][2][25] <-- this one gets ignored by the object data[2018][2][22] Sample Code: var date = new Date(); var data = {}; <?php $eventsNum = 3> &l ...

The absence of transpiled Typescript code "*.js" in imports

Here is an example of the code I am working with: User.ts ... import { UserFavoriteRoom } from "./UserFavoriteRoom.js"; import { Room } from "./Room.js"; import { Reservation } from "./Reservation.js"; import { Message } from ...

Provide users with the option to select a specific destination for saving their file

In the midst of my spring MVC project, I find myself in need of implementing a file path chooser for users. The goal is to allow users to select a specific location where they can save their files, such as C:\testlocation\sublocation... Despite r ...

Utilize jQuery for parsing JSON data

Asking for help here because I am struggling with a seemingly simple task. Here is the JSON data that's causing me trouble: {"name":"cust_num","comparison":"starts_with","value":"01"}, {"name":"cust_name","comparison":"starts_with","value":"ad"}, {"n ...

Is it possible to toggle all parent targets in Bootstrap?

When trying to showcase my point, I believe it is best demonstrated by visiting Bootstrap documentation at https://getbootstrap.com/docs/4.0/components/collapse/ and viewing the "multiple targets section." In this section, you will find three buttons: togg ...

"Efficiently setting up individual select functions for each option in a UI select menu

I've integrated UI Selectmenu into my current project UI selectmenu includes a select option that allows for setting select behavior across all selectmenu options, as shown in the code snippet below: $('.anything'). selectmenu({ ...

Searching for and replacing anchor tag links within a td element can be achieved using PHP

I am currently customizing my WordPress website and I need to update the URL (product link) of the "product-image" on the "cart" page. I have the following dynamic code: <td class="product-name" data-title="Product"> <a href=&q ...

Enhance your data visualization with d3.js version 7 by using scaleOrdinal to effortlessly color child nodes in

Previously, I utilized the following functions in d3 v3.5 to color the child nodes the same as the parent using scaleOrdinal(). However, this functionality seems to be ineffective in d3 v7. const colorScale = d3.scaleOrdinal() .domain( [ "Parent" ...

How can we monitor the value of $route.params.someKey in Nuxt.js?

When working with Nuxt.js, I am trying to keep track of the value associated with a key called key1 in the $route.params. The values for key1 are determined using a function called someFunction(). Is there a way for me to monitor $route.params.key1 as a ...