How can JQuery detect input in the fields?

I have the following HTML code and I am looking to trigger a function based on the input in any of the input fields, regardless of the field number.

<input type="text" pattern="[0-9]*" name="code" maxlength="1" autofocus="autofocus" id="input1" class="input1"/>
<input type="text" pattern="[0-9]*" name="code" maxlength="1" id="input2" class="input2"/>
<input type="text" pattern="[0-9]*" name="code" maxlength="1" id="input3" class="input3"/>
<input type="text" pattern="[0-9]*" name="code" maxlength="1" id="input4" class="input4"/>

I want to simplify this by calling a single function for all input fields.

$("#input1").on('input', function () {
    console.log("this is input1");
});

$("#input2").on('input', function () {
    console.log("this is input2");
});

$("#input3").on('input', function () {
    console.log("this is input3");
});
$("#input4").on('input', function () {
    console.log("this is input4");
});

Answer №1

To target all inputs, you can utilize the following selector: $('input[id^=input]').

The input[id^=input] selector will apply to inputs with ids that begin with input.

$("input[id^=input]").on('input', function() {
  console.log("this is " + this.id);
});

$("input[id^=input]").on('input', function() {
  console.log("this is " + this.id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" pattern="[0-9]*" name="code" maxlength="1" autofocus="autofocus" id="input1" class="input1" />
<input type="text" pattern="[0-9]*" name="code" maxlength="1" id="input2" class="input2" />
<input type="text" pattern="[0-9]*" name="code" maxlength="1" id="input3" class="input3" />
<input type="text" pattern="[0-9]*" name="code" maxlength="1" id="input4" class="input4" />

Answer №2

There are numerous techniques, but one involves selecting all the inputs and triggering the input method.

$("input").on("input", function (e) {
  console.log("this is input", e.target.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="text" pattern="[0-9]*" name="code" maxlength="1" autofocus="autofocus" id="input1" class="input1"/>
<input type="text" pattern="[0-9]*" name="code" maxlength="1" id="input2" class="input2"/>
<input type="text" pattern="[0-9]*" name="code" maxlength="1" id="input3" class="input3"/>
<input type="text" pattern="[0-9]*" name="code" maxlength="1" id="input4" class="input4"/>

Answer №3

When using the jQuery $() query selector function, you can pass in multiple selectors separated by commas.

$("#input1,#input2,#input3,#input4").on('input', function () {
    console.log("This function handles input from all four input fields");
});

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

A tutorial on how to switch classes between two tabs with a click event in Vue.js

I am having an issue with my spans. I want to implement a feature where clicking on one tab changes its color to red while the other remains gray. I have tried using class binding in my logic but it's not working. How can I solve this problem and make ...

Unable to invoke the 'apply' method on an undefined object when configuring directions for the jQuery Google Maps plugin

I've gone through the steps in a tutorial to create a jquery mobile google map canvas here, and have attempted to set it up. However, I keep encountering this error in my JavaScript console: Uncaught TypeError: Cannot call method 'apply' ...

Having trouble centering an icon in a cell within AG Grid?

I am struggling with aligning my checkmarks within the cells of my AG Grid. Currently, they are all left aligned but I need them to be centered. Adjusting the alignment for text is not an issue, but I can't seem to center the material icons. It appear ...

Extracting information from a string with JSON in Javascript

Can you assist me? I have developed a web service that provides a clean string after clicking on the URL: { "PersonID": 125, "Title": "Security Officer", "Company": "TSA", "CellNum": "423-915-3224", "EmergencyPhone": "", "Email": " ...

Utilizing useState() to manage active link state in Navigation bar component

Learning react and new to the framework. Trying to create a responsive navbar component with material-ui. Works fine on medium devices but struggling with updating active link on smaller devices. Navbar.js ... SideDrawer.js ... C ...

Initiating the animation/game loop for a three.js object

I am utilizing angularJS and Three.js for the frontend of my project. The Three.js object is created in the following manner: var ThreeObject = (function() { //constructor function ThreeObject() {} ThreeObject.prototype.init = functio init (){ //initial ...

What is the process of closing a dropdown in Vue 3 JS when clicking on any part of the page?

I am currently working with Vue 3 JS and Tailwind CSS. My dropdown functionality is working correctly, but I want the dropdown to close when clicking anywhere on the page. Initially, Tailwind guided me towards using Popovers and PopoverButtons, which cau ...

Identifying Oversized Files on Safari Mobile: A Guide to Detecting Ignored Large Files in

Mobile browsers such as Safari have a tendency to ignore large files when passed in through the <input type="file">. For example, testing with a 10mb image file results in no trigger of any events - no change, no error, nothing. The user action is si ...

Troublesome Issue with ngAnimate and ngHide: Missing 'ng-hide-animate' Hook Class

I am working on a case where I need to add animation to a DOM object using the ngHide directive: Check out this example here Within this scenario, I have an array of JSON objects: $scope.items = [ {"key": 1, "values": []}, {"key": 2, "values": [ ...

`Manipulating the image source attribute upon clicking`

I need help changing the attr: { src: ...} binding of an img element when a different image is clicked. Here is an example: $(document).ready(function () { var viewModel = { list: ko.observableArray(), showRenderTimes: ...

What is the reason for the continual influx of new users being added to the database?

I have a Node.JS and MongoDB console application where I've implemented adding users in one file and outputting all collection objects to the console in another file. When running the command - node scripts/get_all_users.js, both existing users are di ...

Removing a row from a table seamlessly without the need to reload the page

I am having an issue with my page that displays a list of orders. When a user clicks on a button to delete a row from the table, it only removes the first row successfully. However, when attempting to delete the second or third row, it does not work. Can s ...

Tips on displaying a single column in Bootstrap when only one item is present and switching to two columns when two items are present

Currently, I am utilizing the row class in Bootstrap which contains two columns, one for X and one for Y. There are scenarios where either the X column, the Y column, or both may be present within the row. Since a row can have up to 12 columns, when only t ...

``Is there a reason why JavaScript/jQuery events are not functioning properly within a PHP foreach

Although I have a good understanding of foreach loop in PHP, I am facing a new challenge where the script within the foreach loop only works for the first item. This is puzzling to me and I'm trying to figure out why. In my code, I am retrieving an i ...

Bootstrap allows for multiple items to be displayed on the same line, creating

I am currently utilizing Bootstrap framework and have a total of four items. However, the last item is displaying beneath the other three items instead of being on the same line. The current code snippet is as follows: <div class="text-center linksblok ...

When AJAX is invoked, the HTML content fails to display within a div

The following is the ajax script I am currently utilizing: mypage.php $(".sales_anchor").click(function(e) { e.preventDefault(); var store_username = $("#storeUsername").val(); var store_id = $("#storeID").val(); var sale_id = $(this).a ...

Navigating Google Oauth - Optimal User Sign in Locations on Frontend and Backend Platforms

What are the distinctions between utilizing Google OAuth versus implementing user sign-ins at the frontend of an application, as opposed to handling them on the backend? For instance, managing user authentication in React to obtain the ID and auth object ...

Tips for successfully passing a Prop using the Emotion CSS function

Passing props through styled() in Emotion is something I'm familiar with. For example: const Container = styled("div")<{ position: string }>` display: flex; flex-direction: ${({ position }) => (position === "top" ? "column" : "row ...

Tips for fixing flickering tables and bringing the scrollbar back to the top in your DataTable Forge viewer

Presently, I am working with a DataTable that consists of 100 rows and is being set up using lists. The lists dynamically change based on the selected name from a drop down. To achieve this, I use: $("#datatable").remove(); this.datatable = new Au ...

The functionality of jQuery is not properly integrating with Materialize for hiding select options

For a project I'm working on, I have implemented two Select elements in the HTML code. The second select should only be enabled when the first select meets certain conditions. You can check out the JSfiddle link for reference. $(document).ready(f ...