What is the best way to toggle the visibility of fields on a modal in a Ruby on Rails

I am working on an application that utilizes Rails 4.1 and Ruby 2.1.2. The show.html.erb view for the Assignment Model in this application is as follows:

<h1><%= "#{'Source URL'}"%> <div class="source-url"><%= @assignment.source.url %></div></h1>
<%= link_to new_assignment_contact_path(@assignment), id: 'display_modal', class: "add-btn btn-big" do %>
<i class="i15"></i> Add Contact
<% end %>
<br />
<br />
<table>
  <thead>
    <tr>
        <th>Contact Email Address</th>
        <th>Contact Name</th>
        <th>Title</th>
        <th>Phone</th>
  <th>Notes</th>
    </tr>
  </thead>
  <tbody>
    <% @contacts.each do |contact| %>
        <tr>
            <td><%= contact.contact_email %></td>
            <td><%= contact.contact_name %></td>
            <td><%= contact.contact_title %></td>
            <td><%= contact.contact_phone_number %></td>
    <td><%= contact.notes %></td>
        </tr>   
    <% end %>
  </tbody>      
</table>
<br />
<%= link_to "Completed", change_status_assignment_path(@assignment, status: "Completed"), method: :patch, class: "action-btn" %>

When the user presses the New Contact button, a modal pops up and displays the following form:

    <%= form_for(@contact, url: assignment_contacts_path(@assignment), remote: true) do |f| %>
    <div class="cols">
  <div class="col">
    <div class="field">
      <%= f.email_field :contact_email, autofocus: true, placeholder: "Contact email" %>
    </div>
    <div class="field">
      <%= f.text_field :contact_name, placeholder: "Contact Name" %>
    </div>
    <div class="field">
      <%= f.text_field :contact_title, placeholder: "Contact Title", class: "ico-doc" %>
    </div>
    <div class="field">
      <%= f.text_field :contact_phone_number, placeholder: "Contact Phone Number", class: "ico-phone" %>
    </div>
  </div>
  <div class="col">
    <div class="field">
      <%= f.text_field :contact_domain, placeholder: "Contact Domain", class: "ico-www" %>
    </div>
    <div class="field">
      <%= f.select :notes,  ["404 Not Found", "Page Not Loading", "Site Error", "Web Page Not Available", "Log In Required", "Privacy Error", "Blank Page",  "Redirect Url Change >>", "Contact Form Only >>", "Irrelevant >>"], { prompt: "Notes" }, { class: "ico-globe" }  %>
    </div>
    <div class = "field">
      <%= f.text_field :redirect_url_change, placeholder: "Enter Redirect URL" %>
    </div>
    <div class = "field">
      <%= f.text_field :contact_form_only, placeholder: "Enter Contact Form URL" %>
    </div>
    <div class = "field">
      <%= f.select :irrelevant, ["Foreign Site", "Lead Gen Site", "Job Listing", "Domain For Sale", "Forum", "FAQ", "Other >>"], { prompt: "Select Reason Irrelevant", style: 'display:none'} %>
    </div>
    <div class = "field">
      <%= f.text_field :other, placeholder: "Enter other reason" %>
    </div>
  </div>
    </div>

    <div class="actions">
        <%= f.submit "Submit", class: "action-btn" %>
    </div>          
<% end %>

The :redirect_url_change, :contact_form_only, :irrelevant, and :other fields on the modal are initially hidden using CSS with the display:none property. However, based on the option selected in the :notes select element, the application needs to dynamically display the corresponding field.

In Rails, one way to achieve this is by using jQuery or Coffeescript. I am unsure how to write the necessary jQuery/Coffeescript code for this functionality. Furthermore, since this form is within a modal, I am uncertain about where exactly to place this jQuery or Coffeescript code. I attempted to add a simple alert in the app/assets/javascript/contacts.js.coffee file, but it did not trigger. Am I placing the code in the wrong location?

If you could provide some sample code that accomplishes this task and advise me on where to place it, I would greatly appreciate it.

EDIT: Thanks to Lanny, I managed to get the following jQuery script working in the browser's javascript console:

$("select[name='contact[notes]']").change(function () {
   if ($(this).val() == "Redirect Url Change >>") {
    $("input[name='contact[redirect_url_change]']").show();
    $("input[name='contact[contact_form_only]']").hide();
    $("select[name='contact[irrelevant]']").hide();
    $("input[name='contact[other]']").hide();
  }
  else if ($(this).val() == "Contact Form Only >>") {
    $("input[name='contact[redirect_url_change]']").hide();
    $("input[name='contact[contact_form_only]']").show();
    $("select[name='contact[irrelevant]']").hide();
    $("input[name='contact[other]']").hide();
  }
  else if ($(this).val() == "Irrelevant >>") {
    $("input[name='contact[redirect_url_change]']").hide();
    $("input[name='contact[contact_form_only]']").hide();
    $("select[name='contact[irrelevant]']").show();
    $("input[name='contact[other]']").hide();
  }
    else {
    $("input[name='contact[redirect_url_change]']").hide();
    $("input[name='contact[contact_form_only]']").hide();
    $("select[name='contact[irrelevant]']").hide();
    $("input[name='contact[other]']").hide();
  }
 })

$("select[name='contact[irrelevant]']").change(function () {
  if ($(this).val() == "Other >>") {
    $("textarea[name='contact[other]']").show();
  }
  else {
    $("textarea[name='contact[other]']").hide();
  }
})  

When I open the dialog modal, paste the script into the console, and press Run, it works perfectly. However, it does not run in the actual application. I have tried placing it in both the application.js and contact.js files, but neither option has worked. At this point, since the code functions correctly in the console, I suspect that something needs to be done to load the code into the browser or there may be an interference issue. Currently, Turbolinks is being used in the application, but I do not believe it is necessary.

If someone could assist me with determining where the code should be placed and how to call it, or help troubleshoot any potential interferences, I would greatly appreciate it.

Thank you.

Answer №1

Let's go through the steps...

This is the rule I will implement: If a user selects '404' from the Notes dropdown, we will display the input field for 'redirect_url_change'.

Your specific logic may vary. However, using jQuery selectors in different combinations should help you achieve the desired result.

Here is an example of how to do it using jQuery:

script.js

$(document).on("page:load", function() {
  $("select[name='contact[notes]']").change(function () {
    alert("Hello!");
    if ($(this).val() == "404") {
      $("input[name='contact[redirect_url_change]']").css("display", "block");
    }
  });
});

The alert message is added there for debugging purposes. Sometimes JavaScript can fail silently, making it difficult to figure out why certain events are not triggered. Using alert() helps identify which actions are occurring and which ones are not. This may vary depending on your circumstances.

This script doesn't necessarily have to be placed in application.js file. Instead, it can be inserted into any .js file within the javascripts folder of your Rails application so that it is compiled with your app's JavaScript code.

For further references, please check the following sources:

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

Executing a method in an applet using JavaScript

I am trying to print some information using an applet. The applet is located in the signed qds-client.jar file and has the following code: public class PrintText extends Applet implements Printable { private ClientAccount clientAccount; public Client ...

The sidebar.querySelector method is not working as expected

Attempting to assign an 'active' class to the clicked 'nav-link' element in order for it to stay active on the next page the user navigates to. Encountering an issue with sidebar.getElementsByClassName is not a function showing up in t ...

Attempting to retrieve data from cloud Firestore utilizing keyvalue in Angular

My database stores user information under the 'users' collection. I can access this data using the following code: In my service: users$ = this.afs.collection<Users[]>('users').valueChanges(); In my component: public users = t ...

What criteria should I consider when selecting a JavaScript dependency framework?

When it comes to installing dependencies, how do I determine whether to use NPM or Bower? For example, what distinguishes npm install requirejs --save-dev from bower install requirejs --save-dev? Is there a recommended method, or any guidelines for makin ...

Switching icon images using JQuery based on state changes

I'm attempting to switch the background image of my webpage's "body" element when the user toggles between playing and pausing music icons. This is what the CSS for the "body" element looks like: body { background: url('https://s3-us-wes ...

Error receiving parameter in express route callback function

At the moment, I have been working with a number of routes in Express. Some routes are quite lengthy and tend to look like this: router.get('/api/comments', function(req, res, next){ Comment.find({"user": req.payload._id}).exec(function(err,co ...

What is the way to activate Dynamic ng-model from a controller?

I am implementing a loop in my HTML code where each iteration dynamically creates a model. Here is an example of how the loop looks: <tr ng-repeat="item in voucherItems"> <td><input type="text" ng-model="this['id-' + $index ...

Utilizing DataTables.Net Editor for AJAX data submissions within a C# MVC controller

Hello there, I am currently utilizing the Datatables.net editor jQuery plugin in a C# project. I have a question regarding grabbing the data/value of keyLastName from an AJAX post in order to add it to the Editor's WHERE clause within an MVC Controlle ...

Customizing the placeholder font size in Material UI Autocomplete using ReactJS

Is there a way to change the placeholder font size for Material UI Autocomplete? https://i.stack.imgur.com/x71k2.png <Autocomplete multiple id="tags-outlined" options={top100F ...

Having trouble with the express message! I can't seem to access the template I created

I am looking to receive a notification similar to an alert, as described in this link: https://github.com/visionmedia/express-messages By default, I receive something like this https://i.stack.imgur.com/9XlA9.png If I use a template, I do not get any out ...

Changing the theme of a toggle button in Jquery Mobile when the button is pressed

I have a group of buttons with a specific class <div class="prog-day"> <div class="prog-clear" data-role="controlgroup" data-type="horizontal> <a href="#" data-role="button" data-mini="true" data-theme="b">Clear</a> ...

What advantages does incorporating SSR with dynamic imports bring?

How does a dynamic imported component with ssr: true differ from a normal component import? const DynamicButton = dynamic(() => import('./Button').then((mod) => mod.Button), { ssr: true, }); What are the advantages of one method over the ...

Displaying sorted objects from Angular serviceIn Angular 8, let's retrieve an object

In my Angular8 application, I am running a query that fetches a data object. My goal is to sort this data object based on the order value and then display each product item on the browser. For example, here is an example of how the output should look like ...

I'm trying to set an object value for this select element, and while I have managed to do so, I am struggling to display the title of the selected object. Can anyone help me

I am struggling to display the title of the selected object in this select element. Can anyone help me understand why my code is not showing the title? Here is the code snippet: const [selectedCategory, setSelectedCategory] = useState(""); const categor ...

Locate elements based on an array input in Mongoose

Define the Model: UserSchema = new Schema({ email: String, erp_user_id:String, isActive: { type: Boolean, 'default': true }, createdAt: { type: Date, 'default': Date.now } }); module.export ...

Storing Radio Buttons and Checkboxes Using LocalStorage: A Simple Guide

Is there a way to save and retrieve values from localStorage for input types "radio" and "checkbox"? I've tried using the same code that works for text and select elements, but it doesn't seem to be saving the values for radio and checkbox. Can s ...

Modifying Element Values with JavaScript in Selenium using C#

As a newcomer to automation, I am facing a challenge with automating a web page that has a text field. I initially attempted using driver.FindElement(By.XPath("Xpath of elemnt").SendKeys("Value"); but unfortunately, this method did not work. I then resor ...

Managing MUI form fields using React

It seems like I may be overlooking the obvious, as I haven't come across any other posts addressing the specific issue I'm facing. My goal is to provide an end user with the ability to set a location for an object either by entering information i ...

Remove the underline from links in gatsbyjs

When comparing the links on (check source code https://github.com/gatsbyjs/gatsby/tree/master/examples/using-remark), they appear without an underline. However, on my blog (source code here: https://github.com/YikSanChan/yiksanchan.com), all links are un ...

Issue with AJAX and Jquery auto form update functionality malfunctioning

On my form page, here is the code snippet: <form action="/register-process" method="post" id="form1"> <script type="text/javascript"> jQuery(document).ready(function($) { $(document).on('focusout', '#dateenglish', function ...