Internet Explorer 10 not triggering the 'input' event when selecting an option from the datalist

Within this particular scenario, there is an input field paired with a corresponding datalist element. My aim is to develop JavaScript code that actively listens for when a user chooses an item from the list. Most resources suggest utilizing the "input" event handler for this task, and in browsers like Chrome and Firefox it functions seamlessly. However, Internet Explorer presents a challenge.

In IE10, I have observed the following behavior:

  • Tapping into the field triggers the event.
  • The event does not trigger upon initial selection of an item from the datalist.
  • Re-selecting the same option successfully fires the event.

To demonstrate, here's a test:

https://i.stack.imgur.com/f7Eqn.gif

$('input').on('input', function(){
    console.log($('input').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input list="ice-cream-flavors" id="ice-cream-choice" name="ice-cream-choice" />

<datalist id="ice-cream-flavors">
    <option value="Chocolate">
    <option value="Coconut">
    <option value="Mint">
    <option value="Strawberry">
    <option value="Vanilla">
</datalist>

If anyone has any insights on how I can compel Internet Explorer to trigger the desired event (or any event) so that I may execute a function upon user selection, I would greatly appreciate it.

Answer №1

Encountered the same issue on IE11 with a custom autocomplete list inspired by https://www.w3schools.com/howto/howto_js_autocomplete.asp

After some testing, it became apparent that IE11 was triggering the input event when clicking away from the input box (losing focus), contrary to other browsers that only fired this event upon text entry.

The workaround involved implementing a check for changes in the input value specifically for IE:

function inputEventGeneral(input, fn) { //input event for any browser
    if (checkBrowserIE()) {
        inputEventIE(input, fn);
    } else {
        input.addEventListener('input', function (e) { //normal input event for Chrome, FF, etc.
            fn(this); //run this function on input
        });
    };
};

function inputEventIE(input, fn) { //input event for IE
    let curr = '';
    let prev = '';

    input.addEventListener('input', function (e) {
        curr = this.value;

        if (prev === curr) { //check if value changed
            return;
        };

        prev = curr; //update value of prev

        fn(this); //run this function only if the value has been changed
    });
};


function checkBrowserIE() {
    return (/Trident/.test(navigator.userAgent)); //https://stackoverflow.com/questions/22004381/ie-input-event-for-contenteditable
};

Additionally, in IE, there's an issue with the clear button ('x') on text input fields not triggering an input event with the provided code. To address this, you could either a) hide the clear button using CSS:

input[type=text]::-ms-clear { display: none; }

or b) adjust the code to store the value of prev in a data-prev attribute or a global variable and update it whenever the input form value changes (such as selecting from the autocomplete list/datalist). This modification would ensure the event fires upon clicking the clear button since the prev value (val) will differ from the curr value ('') when clearing the field.

Hopefully, this information proves helpful!

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

The variable is unable to transfer successfully from JavaScript to PHP using ajax

I have a code that is designed to pass the values of all checked checkboxes to a PHP file in order to delete corresponding rows from a CSV file. The checkbox values are dynamic. <tr><td><span class="custom-checkbox"><input ty ...

Toggle the backgroundImage visibility by setting it to either hidden or displayed using jquery

$('.arrow').css("background-image", "url('../img/arrow.png')").hide(); I have implemented a custom solution using CSS and jQuery to hide the downward arrow when scrolling down on my webpage. `$( document ).ready(function() {
 co ...

I'm just getting started: an image carousel featuring a unique twist with random quote overlays, but there's a catch - it only activates on the very first image... what comes next?

After successfully displaying the generator over the first image, I encounter a problem with the second and third images where it seems to disappear. However, upon cycling back to the first slide, the generator reappears with a different quote. I've a ...

An issue has arisen with loading chunks in Ionic 5/Angular, possibly due to an un

I am currently working on enhancing the offline capabilities of my Ionic 5 app. To achieve this, I have implemented a strategy where data is stored in SQLite while the app is connected, and then retrieved from SQLite when offline instead of making HTTP req ...

Obtain redirected JSON data locally using Angular 5

Currently, I am working on retrieving JSON data which will be sent to my localhost through a POST method. The SpringBoot API controller will validate the JSON content before forwarding it to my localhost. My task is to intercept this JSON data when it is t ...

Show the div just one time

Hey there, I'm trying to create a StackOverflow-like message display at the top of my page. Everything is set up and configured, but I'm facing an issue - the message only shows up the first time. After that, it disappears. I've read that ...

Why is IE waiting to load XML content until I access Developer tools?

I'm encountering an issue with my webpage where the product information loaded from an XML file using a jQuery AJAX get request works fine in Firefox and Chrome, but for some reason it doesn't load in Internet Explorer. Oddly enough, it does load ...

React: Avoid the visible display of conditional rendering component fluctuations

In my current React project, I am developing a page that dynamically displays content based on the user's login status. The state variable "loggedIn" is initially set to null, and within the return statement, there is a ternary operator that determine ...

Preventing PCs from accessing a specific webpage: A step-by-step guide

I am currently using the code below to block phones: if { /Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i .test(navigator.userAgent)) { window.location = "www.zentriamc.com/teachers/error ...

Capture the response from an AJAX request and store it in a JavaScript variable

I've been struggling to find a solution for this issue for quite some time now without any success. Here's what I'm trying to accomplish: I need to retrieve an array from my PHP file so that I can utilize it in my JavaScript code. Example. ...

Using a union type annotation when passing into knex will result in the return of an unspecified

Knex version: 2.5.1 Database + version: postgres15 When passing a union typescript definition into knex as a type annotation, it returns the type any. However, by using type assertion as UserRecord, we can obtain the correct UserRecord type. It is my un ...

Ways to navigate through a webpage without encountering any overflow issues

My window is too small to scroll, but I still need the ability to do so. Is it possible to scroll even when the height of the container is not large enough to display the scrollbar? Below is the code I am using to achieve scrolling: setTimeout(function() ...

Tips for declaring a particular type during the process of destructuring in Typescript

I have my own custom types defined as shown below: export type Extensions = | '.gif' | '.png' | '.jpeg' | '.jpg' | '.svg' | '.txt' | '.jpg' | '.csv' | '. ...

A more efficient method for passing a function as an argument using the keyword "this"

When it comes to passing a function as an argument that uses the this keyword, is there a preferred method or correct way to do so? An example would be helpful in understanding this concept better: For instance, if I want to fade out an object and then r ...

To ensure that quotes are correctly handled in a string being passed to a JavaScript function within an `onclick`

I am facing an issue with a cycle in a jspx file that I have. The cycle looks like this: <c:forEach var="var" items="${dataFile.list.rows}"> <li> <div> <a href="#" onClick="myFunct('${var.url}','escape(${var ...

The sluggish rendering speed of AngularJS is causing a delay in displaying the loader

Within my application, I have tabs that load a form in each tab with varying numbers of controls. Some tabs may contain a large number of controls while others may have fewer. My goal is to display a loader while the contents are being rendered into the HT ...

What are the common issues with Angular 2's ng-if directive?

I am completely new to working with Angular and have already gone through all the ng-if related questions without finding a solution that fits my issue. Here is my code: <tr *ngFor="#position of positions"> <td> ...

Implementing custom CSS styles for HighCharts API pie chart drilldown labels

I successfully created a pie chart using highcharts and configured the chart with the following options: chart: { type: 'pie', }, In order to change the width of the text on the chart, I added the following options which force e ...

how to handle form submission using JavaScript's return method

As a developer, I have created a single page that fetches data from a registration page. On this page, each data row has an "add" and "unfriend" button, with the latter initially disabled. When a user clicks the "add" button, a prompt box appears asking ...

The success function of the Ajax request remains untouched by the response

My ajax call isn't triggering the success:function(resp){ ...} Despite receiving a response status of 200 and a non-null Json response. This is my ajax setup: $.ajax({ url: '/url/', type: 'GET', data: { pass_ ...