Improving the form fields and Stimulus JS by eliminating the need to repeat the :data-action attribute for each individual field

I'm working with the following form

<%= 
  form_for(
    model,
    html: {
      :'data-controller' => 'enable-submit-button-if-fields-changed'
    }
  ) do |form|
%>
  <%= form.text_field(:title, :'data-action' => 'input->enable-submit-button-if-fields-changed#enableSubmit') %>
  <%= form.text_area(:description, :'data-action' => 'input->enable-submit-button-if-fields-changed#enableSubmit') %>
  <%= form.file_field(:picture, :'data-action' => 'input->enable-submit-button-if-fields-changed#enableSubmit') %>
  <%= form.check_box(:delete_image, :'data-action' => 'input->enable-submit-button-if-fields-changed#enableSubmit') %>
  <%#= other input fields... %>
<% end %>

and here is a Stimulus JS controller related to it

import { Controller } from "@hotwired/stimulus"

// Connects to data-controller="enable-submit-button-if-fields-changed"
export default class extends Controller {
  connect() {
    this.element.querySelector('input[type=submit]').disabled = true;
  }

  enableSubmit() {
    this.element.querySelector('input[type=submit]').disabled = false;
  }
}

The purpose of these components is to activate the submit button when any input field changes.

In the form code above, I specified

:'data-action' => 'input->enable-submit-button-if-fields-changed#enableSubmit'
for each input field individually. Is there a way to streamline this process and avoid repetition by only declaring
:'data-controller' => 'enable-submit-button-if-fields-changed'
on the form itself, and then have all internal input fields automatically trigger the JavaScript function to enable the submit button upon change? Or should I continue to repeat :'data-action' for each field?

Answer №1

If you want to simplify your code, consider attaching a single event listener to the form element since the input event will propagate up through the DOM hierarchy.

For more information on the input event in the HTMLElement API

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

Page experiencing issues with JavaScript functionality

Here is a simple function that I am using to shake a form when the user's email is not valid: function shakeForm() { var l = 10; for( var i = 0; i < 10; i++ ) $("form").animate( { 'margin-left': "+=" + ( l = -l ) + 'px ...

What are the signs indicating that I've reached the threads limit set in Node.js?

My current configuration includes a thread pool size of 25. process.env.UV_THREADPOOL_SIZE = 25; How can I verify at runtime that all the threads have been used up? Is there a method to detect when all defined threads have been utilized when a new reque ...

The checkbox labeled "Shipping Same as Billing" is not functioning correctly. I have included my JavaScript code below, can someone please help me identify what I am overlooking? (Only JavaScript code is provided; HTML is

I'm having trouble transferring data from a 'shipping' address to the 'billing' address section. I've included all my code, but nothing seems to copy over when the check box useShip is selected. All the HTML code is provided f ...

Utilizing VueJs (Quasar) to access vuex store within the router

Recently, I have been diving into learning Vuex and creating an authentication module. Following a tutorial, I reached a point where I needed to use the store in the router. However, after importing my store at the top of the router index.js file, I notice ...

The constructor window.CCapture is not valid in Node.js environment

Can anyone help me figure out how to load CCapture in Node.js without using a headless browser for recording canvas stream? Every time I try, I keep running into the error message saying "window.CCapture is not a constructor." If you are familiar with the ...

What are some well-reputed JavaScript grids that can be populated with data using AJAX requests?

Looking for a grid that can be dynamically updated with ajax requests. The ability to sort, filter, and select items is essential. Your help is greatly appreciated! ...

Creating a Form set with Django's SesionWizardView

I am looking for assistance with using Formsets in Django as I have been unable to find the necessary information online. https://docs.djangoproject.com/en/1.4/ref/contrib/formtools/form-wizard/ I am attempting to create an example following this documen ...

Setting a timer within Vuex - step by step guide

I recently delved into learning Vue and Vuex. My current project involves setting up a countdown timer that initiates a countdown from 5 seconds upon being clicked. The implementation logic resides in the Vuex store for efficient state management, but unfo ...

Prevent certain output files from caching in Vue CLI 3 to avoid busting the cache

I am currently developing a chrome extension using vue cli 3 and have successfully implemented the basics. However, I would like to streamline my file structure by including my content and background javascript files in the build process instead of manuall ...

Difficulty encountered when attempting to transmit JavaScript object to Python Flask using JSON

When attempting to POST a JSON string to Python Flask using ajax, I encountered the following error: Error This is the JavaScript code snippet: $.ajax({ type: 'POST', url: window.location.href, data: JSON.stringify(questionObj0), dataType: &ap ...

Error: Identifier Not Expected (Exploring Generators in ES6)

After delving into the information provided in the generators documentation on MDN, I devised a straightforward experiment: var nodes = { type: 'root', value: [ { type: 'char', value: 'a' }, { type: &ap ...

The absence of the 'Access-Control-Allow-Origin' header is causing an issue

Utilizing angular.js, I am developing a ReSTful app for mobile devices using cordova. For the server-side aspect, I have opted to use the slim framework following this tutorial: () However, upon uploading the api folder to the server, an error arises: "No ...

Step-by-step guide on Setting up the bronto.sca.cart object using Bronto JSON

I have implemented the Bronto Tag Manager to track cart details successfully. After including the Bronto Commerce JavaScript snippet on my page, I am now able to create the bronto.sca object. While bronto.sca.config() and bronto.sca.id are returning valu ...

How can I retrieve related elements within jQuery UI autocomplete?

I'm trying to enhance jqueryUI's autocomplete functionality by sending extra parameters in a more generic way. Below is a simplified version of the HTML code I'm working with: <form id='employees'> <input class='a ...

The issue of Nodejs Messenger broadcast message functionality being inoperative

Trying to initiate a broadcast through my Facebook Messenger bot, I have implemented the following code: if (subscribe === true) { // Initiate HTTP request to Messenger Platform request({ "uri": "https://graph.facebook.com/v2.11/me/broadcast_messa ...

What steps do I need to take in order to implement a functional pagination menu in Vue?

I downloaded and installed laravel-vue-pagination with the following command: npm install laravel-vue-pagination After that, I globally registered it in my app.js file: Vue.component('pagination', require('laravel-vue-pagination')); F ...

Revise if a specific file is not being called by AJAX

I am currently utilizing a routing library known as Grapnel.js. It requires URLs in the format of index.php#something/something, which is why I am using htaccess to rewrite /something/something to match that structure. However, I would like the flexibility ...

Is there a way for me to import a variable from one file and use require() to access it in another file?

This is my current folder structure: collegesapp -- |-- node_modules -- express | -- connect | -- jade | -- passport |-- routes -- routes.js ...

React is unable to identify the `activeStyle` property on a DOM element

Is there anyone who can help with this error message? The warning states: React does not recognize the activeStyle prop on a DOM element. If you want it to be a custom attribute in the DOM, use activestyle in lowercase instead. If it was accidentally pas ...

JavaScript code for iframe auto resizing is not functioning properly on Firefox browser

I have implemented a script to automatically resize the height and width of an iframe based on its content. <script language="JavaScript"> function autoResize(id){ var newheight; var newwidth; if(document.getElementById){ newh ...