What is the best way to output neat and tidy JavaScript code from a custom view helper in Rails

As I was working on my update.js.erb file using Rails 3, I realized that I was repeating a lot of code. To simplify things, I attempted to move it all into a helper function. However, I encountered an issue where the helper was not producing clean JavaScript output. Instead of ", it kept inserting \" throughout the script.

This is how I initially set up the code:

<% if @list.show_today %>
    $("#show_today_check_<%= @list.id %>").removeClass("gray").addClass("orange").attr("value","0");
<% else %>
    $("#show_today_check_<%= @list.id %>").removeClass("orange").addClass("gray").attr("value","1");
<% end %>   

...

Below is the helper function I created to generate the above JavaScript:

def toggelButtonState( object, name, color)

    if object.send(name)
      @add_col = color
      @rem_col = 'gray'
      @value = "0"
    else
      @add_col = 'gray'
      @rem_col = color
      @value = "1"
    end

    js = '$("#'
    js += "#{name}_check_#{@list.id}"
    js += '").removeClass("'
    js +=  @rem_col
    js += '").addClass("'
    js +=  @add_col
    js += '").attr("value","'
    js += @value
    js += '");'

end

Calling the function like this:

<%= toggelButtonState( @list , 'show_today', 'orange' ) %>

Results in the following response:

 $(\&quot;#show_today_check_2\&quot;).removeClass(\&quot;orange\&quot;).addClass(\&quot;gray\&quot;).attr(\&quot;value\&quot;,\&quot;1\&quot;);

I noticed a similar issue with HTML content in helpers and discovered the use of content_tag. Is there an equivalent method for handling JavaScript? How can I eliminate the insertion of \&quot;'s?

Answer №1

Insert

js.html_safe

at the end of the toggelButtonState function

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

Exploring the depths of deep populating in Mongo and Node.js

I am currently struggling with a complex data population issue. var commentSchema = mongoose.Schema({ name: String }); var userSchema = mongoose.Schema({ userId: { type: String, default: '' }, comments: [subSchema] }); var soci ...

What is the best way to structure a nested JSON object to align with a nested HTML form layout?

Currently, I am working on a form that is structured using tabs, optional fieldsets, and various field elements in HTML. Below is a simplified representation of the structure: div.tab1 div.fieldset3 div.container308 div.container314 div.fieldset4 d ...

What is causing my React-Testing Library queries to not work at all?

In my current project, I am using Jest along with Testing-Library to create UI unit tests. One issue that I encountered was that the components were not rendering on the DOM. After some investigation, I found that the main culprit was a component called & ...

React JS is not allowing me to enter any text into the input fields despite my attempts to remove the value props

Currently, I am working on creating a Contact Form using React Js. I have utilized react bootstrap to build the component, but unfortunately, when attempting to type in the input fields, the text does not change at all. import React, {useState} from ' ...

Make sure that the iframe loads the next page with enough force to break out

My dilemma involves an iframe that loads the new tab page. When a user clicks on the thumbnail, it opens within the iframe. My goal is to have any subsequent load in the iframe redirected to window.top. Is there a way to achieve this without manually setti ...

Is there a way to deactivate keyboard input on an HTML number input field? How about in a React or Material-UI environment?

I am working with an <input> tag that has the attribute type="number", and I want to disable keyboard input so that users are required to adjust the value using the spinner (up and down arrows). This will allow me to consume the input value on each c ...

Using animation.width() in Javascript to create a countdown

Currently, I am working on creating a visual countdown for my users to indicate when an animation will finish. The code snippet below shows my initial attempt: function setClassAndFire(){ timer = setInterval(function () { t--; ...

Troubleshooting Problem with Bootstrap CSS Menu Box Format

I'm having trouble creating a simple menu for my Bootstrap site. What I want to achieve is something like this: https://i.sstatic.net/abZXC.png This is what I have accomplished so far: https://i.sstatic.net/JFVC2.png I've attempted to write th ...

The Evolution of Alternatives to contentEditable

Related: ContentEditable Alternative I am curious about the timeline of online WYSIWYG editors prior to the existence of contentEditable. I remember using GDocs and GMail with rich-text features that functioned similarly to contentEditable. I would appre ...

What is the best way to trigger useEffect when the state being used within the effect is expected to change during the course of the effect's

Exploring the following code snippet: const [list, setList] = useState([]); const [curPage, setCurPage] = useState(0); const fetchItem = useCallback(async ()=>{ const data = await callAPI(); // data is an object setList(prev => [...prev, data]) ...

Working with Rails involves utilizing Single Table Inheritance and SQL, where tables are referred to as "subclass" rather than class

In my current configuration, the model Client is a subclass of the model Contacts. The STI table is named contacts. However, I encountered an error in my test code when trying to execute: it "should have the right clients in the right order" do @produc ...

Retrieve the selected date from the date picker widget

Welcome to my custom datepicker! Here is the HTML code: <div class="field-birthday field-return" id="birthday-edit" style="display:none;"> <div class="birthdaypicker"></div> <input class="hidden" name="birthday" type="hidden" ...

Failure of AJAX HTML function to retrieve value from textarea

I am displaying data in the first three columns of a table, with the last column reserved for user feedback/comments. However, when the form is submitted, the values in the textarea are not being posted. The table has 6 rows. The Sample TR: <tr> &l ...

transferring a string parameter from PHP to a JavaScript function

I have been searching for a way to transfer a string (stored as a variable $x) from PHP to JavaScript. I came across several code solutions, but I am wondering if these strings need to be declared as global variables? Even after declaring it as a global va ...

Nodejs and express authentication feature enables users to securely access their accounts by verifying their identity before they

I am currently working on a straightforward registration page that needs to save user input (name, email, password) into a database. My tools for this task are express and node. What I am experimenting with is consolidating all the database operations (suc ...

Can you come up with a catchy one-liner for an array that contains all the elements of the arrays that came

I am currently working with the array [1,2,3,4,5,6,7,8,9] My goal is to achieve [ [1], [1,2], [1,2,3], [1,2,3,4], [1,2,3,4,5], ... ] I envision the desired outcome as const var = array.reduce **using some form of black magic** I ...

Encountered an error when attempting to load resource: net::ERR_CERT_AUTHORITY_INVALID following deployment on Vercel

I recently deployed a chatUI-app on Vercel that fetches chats from an API located at "http://3.111.128.67/assignment/chat?page=0" While the app worked perfectly in development, I encountered an issue after deploying it on Vercel where it ...

Issue with Angular 2 (Ionic 2): Struggling to properly display Component within Page

I have successfully created an Angular 2 Component: import {Component, View} from 'angular2/core'; @Component({ selector: 'sidemenu' }) @View({ templateUrl: 'build/pages/menu/menu.html', }) export class Menu { } Howev ...

Create a unique functionality by assigning multiple event handlers to a single event

I am looking to add a JavaScript function to an event that already has a handler function. The new function should complement the existing one rather than replace it. For instance: There is a function named exFunction() that is currently linked to docume ...

How can you update an image's source when hovering over it?

My goal is to switch the image source upon mouseover using a combination of asp.net and javascript. Here is the code I am currently using: <asp:ImageButton id="button" runat="server" Height="65px" ImageUrl="~/images/logo.png" OnMouseOver="src='~ ...