One-stop solution for incorporating text, checkboxes, and select input in a single event using Jquery

When certain events occur on a form, I need to perform some actions:

1) Modify the value of an input text box using the keyboard or mouse (pasting) 2) Check/uncheck a checkbox 3) Change the selected option in a select dropdown

Currently, I am handling these events individually like this:

$(':text').on('input', function()  {
  //Code 
}

$(':checkbox').on('change', function()  {
  //Code
}

$('select').on('change', function()  {
  //Code
}

However, I would like to consolidate all these event handlers into a single function like this:

$(':text, :checkbox, select').on('???', function()  {
      //Code   
    }

I would appreciate any help with this. Thank you.

Best regards

Answer №1

This code snippet demonstrates how you can handle both change and input events for checkboxes, text inputs, and select elements.

$(':checkbox, :text, select').on('change input',function(e) {
    // Your code here
});

JSFIDDLE

Answer №2

Make sure to assign a CSS class to these input fields and utilize that class as your jQuery selector for attaching your event listener.

HTML

<input type="text" class="editable" />
<input type="checkbox" class="editable" />

jQuery Code

$(function(){
   $(document).on("change", ".editable", function(event){
      var element = $(this);
     // Perform desired actions here.
    }); 
});

Answer №3

If you're looking for a scalable and user-friendly solution, I recommend following @Shyju's advice. However, I have provided an implementation based on your question.

To listen to click events on the document and delegate them to the selectors you specify, use the following code:

$(document).on('click', ':text, :checkbox, select', function()  {
  doFunction();
});

For a live example, check out this JSFiddle demo

Answer №4

Connect your individual or multiple events to various elements by utilizing the class attribute. Apply the same class to all elements and determine which event type has been triggered. Modify your implementation based on the triggered event code.

Give this method a try:

HTML :

<input class="elements" type="text" />
<input class="elements" type="checkbox" />
<select class="elements">
    <option>A</option>
    <option>B</option>
    <option>C</option>
</select>

<input class="elements" type="button" value="Click here" />

jQuery :

$(".elements").on("change click", function(e){
    var nodes = e.target;
    if(nodes.nodeName == "INPUT"){
        if(nodes.type == "text" && e.type == "change"){
            // implement code here
            alert("Input changed");
        }else if(nodes.type == "checkbox" && e.type == "change"){
           // implement code here
            alert("Checkbox state changed");
        }else if(nodes.type == "button" && e.type == "click"){
            alert("Button is clicked");
        }
    }
    else if(nodes.nodeName == "SELECT" && e.type == "change"){
        // implement code here
       alert("Select option changed");
    }
});

jsFiddle

References :

event.type

event.target.nodeName

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

Failed to authenticate with the database server located at `localhost`. The credentials provided for `root` were found to be invalid - Nextjs & Prisma

I've recently been involved in a Next.js project where I am using Prisma as the database. However, I am encountering an issue when attempting to establish a connection to my database - despite providing what I believe to be the correct username and pa ...

Having trouble resolving '@auth0/nextjs-auth0' during deployment on Vercel? Check out this error message: "Can't resolve '@auth0/nextjs-auth0' in '/vercel/path0/pages'"

I recently deployed a project on Vercel and have been working on enhancing the layout to achieve a minimum viable product (MVP). As part of this process, I decided to switch my authentication method to @auth0/nextjs-auth0 package for Next.js. After running ...

What are the steps to add a Search Box to my HTML Website?

Currently, I am in search of a way to incorporate a "Search" feature on my website that is built solely with HTML. I have added a Search box for the users but I'm uncertain about how to proceed next. Can I use PHP to enable the Search functionality o ...

Comparing the Absolute anchor tag to the anchor tag with an absolute span

I have come across two methods for extending a link over a card, container, div, or any other element in order to make the entire area clickable. The first approach involves positioning the <a> tag as an absolute element. The second method keeps th ...

A guide on storing data in a database with AngularJS within the Django framework

My project utilizes the Django framework along with AngularJS. I am looking to save all the values entered in my HTML page to the Database upon clicking submit. I have heard that a simple submit button is needed and most changes will be made in views.py. S ...

The function of jQuery .on will not be effective when applied to elements that have been

Currently, I am experimenting with some functionality to trigger an action when hovering over a specific element (such as a link) in order to display something in the console. I came across this helpful answer here, which mentions that "you can define you ...

Is there a way to enlarge the font size for a complete tag?

I'm having trouble with a project. One of the tasks is to use jQuery or JavaScript to increase the font size of a paragraph. The console statements are incrementing by +1 with every mouse click (the first click adds 1, the second adds 2, and so on). ...

Exploring Angular's Observables for handling HTTP requests

Exploring Angular Observable Documentation As I delved into the Angular observable documentation mentioned above, I came across a section that compares promises with observables. Observables provide many values, while promises provide one. This characte ...

The loop within a loop is causing excessive lag and is on the verge of crashing the

I need help with optimizing the performance of my app that retrieves json data. The json file contains nearly one thousand words structured like this: {"THEMES":{"THEME1":["ITEM1","ITEM2","ITEM3"],"THEME2":["ITEM1",...]...}} The size of the file is aroun ...

Recover Checkmark Status from Data

Currently, I am storing form data in json format and encountering an issue when trying to load values from a previously created json file. The plain old JavaScript function provided below successfully loads values into a form from a file, effectively resto ...

An alternative way to show time zones such as PT and ET instead of using PST and EST with the help of moment

For efficiency in table space using moment.js, I am looking to utilize PT/ET instead of PST/EST. HTML- {{ moment.tz([2012,0],timezone).format('z')}} // It displaying EST/PST but I need only ET/PT. Note: The timezone is dynamic, so regardless of ...

Display elements exclusively within this particular format

Here is my HTML form: <div class="question"> <td class="status1"> <form action="update.php" method="post" id="form-id" enctype="multipart/form-data"> <div class="recstatus">$row[12]</div> ...

Creating a custom front page in WordPress with a custom post type post

After using the CPT UI plugin in WordPress to create a custom post type, I am now facing the issue of not being able to display these posts on the front page by setting the 'reading' option in the admin panel. How can I go about displaying them p ...

Image Link for Facebook

Just finished designing and launching this website: However, when our administrators try to share a link on Facebook, the post shows an icon that doesn't quite match our company branding: Is there any way to change the icon displayed? The 'v&ap ...

Having trouble adding animation to button element following the application of :after pseudo-element styling

I've been grappling with pseudo elements, but I just can't seem to make a simple button animation work using them. My goal is to have a panel move from bottom to top on hover. Similar to the button found on this page (1st row, 2nd button). From ...

Conceal on External Click with AngularJS

My code looks something like this... I am using the 'left-menu-active' class to toggle the menu in css... I have two issues and I am looking to resolve them using angular js... I want to dynamically add a class to the parent element using angu ...

insert a new user into a MongoDB collection

I am facing an issue with adding a user to my collection called users. The code I'm currently using is: var user1 = { Username: "joonyoftv", Password: "joon123", Email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Tips for adding a solid background color to a div element

I am struggling with trying to make a full width background-color for a div in my ruby on rails app. Despite setting the background color and margin to 0, I still end up with unwanted margins on the left, right, and top. Below is the code snippet: <!D ...

Guide on incorporating a PHP file into a div using jQuery

This JavaScript function is used to load a given date in the page. It removes the 'selected' class from all date elements, adds the 'selected' class to the clicked date element, and then fetches data related to that date using an AJAX c ...

An unanticipated SyntaxError was encountered while attempting to utilize an Ajax post, specifically in relation

I can't seem to figure out how to troubleshoot an ajax/jquery error. Here is the function I'm working with: var LogIn = { Email: $("#Name").val(), MobileNo: $("#txtMobileNumber").val(), PinCode: '', ...