Manipulating Select2 without using jQuery

Is there a way to manage the component programmatically without using jQuery? I need to execute this code through Selenium, and since I cannot access the jQuery object (as it's bundled with Webpack), I have to control it using pure JS.

I attempted to simulate a user click like this:

document.getElementById('select2').click()

However, the dropdown does not open. My goal is to:

  1. Open the Select2 dropdown
  2. Type something in the search box to trigger an ajax call and display possible options
  3. Select an option by its text

Answer №1

After dedicating a good 3-4 hours to the task, I delved into the select2 source code and managed to discover a method for initiating the opening of a select2 box.

package.json:

"select2": "^4.0.13"

#example (<select id="example"></select>)

//Locate element for dispatchEvent
const element = document.querySelector('#example + span > .selection > span');
//Trigger select2 to open select
element.dispatchEvent(new MouseEvent('mousedown', {
   which: 1,
   view: window,
   bubbles: true,
   cancelable: true,
}));

Answer №2

For a solution, you can attempt using this alternative method:

document.querySelector("#example + span > .selection > span")
and then simulate a click event. Feel free to test it out by visiting this Fiddle link: https://jsfiddle.net/zeLbk6s3/2/

Remember to trigger the "click" action on the correct element.

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

What is the proper way to attach the form tag action value in an EJS template?

Does anyone know about this? I am currently testing some JavaScript code: function mem_join_next() { if (document.mem_join.email.value == "") { alert("please input your email ID"); document.mem_join.email.focus(); return; } documen ...

Struggling with getting Sprite maps to function properly within THREE.js

I'm having some trouble adding a sprite to my scene in the usual way. The image I'm using can be found here: i.imgur.com/kMT4mOH.png var map = THREE.ImageUtils.loadTexture('i.imgur.com/kMT4mOH.png'); var mat = new THREE.SpriteMaterial( ...

Is it possible to create a Nuxt.js static website that incorporates a dynamic single-page application built with Vue.js

Currently researching Static Site Generators for a client project, I discovered Vue.js and Nuxt.js, which appear promising. Given the choice between Vue.js and React, I lean towards Vue at the moment. The client's website consists of 120 pages with s ...

Make the buttons stretch across the width of the window

When the App is launched, it will display two buttons in the footer by default. If users interact with the app in a certain way, a third button may need to be added. However, based on other user selections within the app, this button may also need to be ...

Issue with Transmitting Selected Value from Select Menu to the Server

(I'm a backend developer dipping my toes into front end development) I've got a basic HTML form with text field inputs and a select menu. When I submit the form, I can see the text field values being sent to the server, but oddly, the value for ...

Tips on customizing the color of checkboxes in a ReactJS material table

I'm working on a project that involves using the Material table, and I need to change the color of the checkbox when it's selected. Can anyone help me with this? https://i.stack.imgur.com/JqVOU.png function BasicSelection() { return ( <M ...

The search results table does not exhibit the same behavior as the original table

I needed to enable the search function on my employee table, but encountered an issue when I implemented it - the search results were displayed on a separate page from the original table. To resolve this, I copied the table population code from the origina ...

Configuring Next-auth CredentialProvider and setting up redirection

I'm feeling a bit lost when it comes to understanding how the credentials provider and redirects work. The documentation mentions that the credentials provider doesn't support a callback and is specifically for OAuth providers, which I understand ...

Why is my return statement in JavaScript Nextjs mapping values twice?

I am running into an issue where my code is displaying the output twice, and I can't seem to figure out why. Any assistance would be greatly appreciated. Here is a link to the current output that I am receiving. I suspect that the problem lies in sett ...

Concealing messages in React after a brief period

The task at hand involves making a message disappear after 5 seconds. In the following code snippet, I have a scenario where clicking on the "Generate Room Name" button will populate a URL in a text box. After copying this URL using the Copy button, a mes ...

Horizontally align the list items within a div that has overflow:auto

Currently, I am working on a timeline project and have the following code: $("#time-line-selector ul li a").click(function(event) { event.preventDefault(); $("#time-line-selector ul li a").removeClass("active"); ...

What is the method to display a group label using ng-table?

Does anyone have experience creating a group in ng-table? <div> <div ng-controller="ContractsController" style="position: relative;background:whitesmoke; border:1px solid lightgray; border-radius:5px; margin-top:0px; margin-bottom:5px; h ...

Is it possible to assign variables inside an http call from a function in AngularJS?

Seeking urgent assistance. I need help with a function that resembles the following: $scope.getData = function(id) { $http.get('/url' + id).success(function (data) { return data.a.b.c; }); }; In another function, I have the fol ...

Next.js Content Switching: A Step-by-Step Guide

On my app, I have a main dashboard featuring a sidebar navigation and content container. However, being new to next.js and its routing system, I'm unsure how to update the content when a user navigates using the sidebar. Do I need to create separate p ...

Origin Access Control - Failing to Function

I've been working with a PHP API that authenticates credentials. In the beginning of my PHP script, I include these lines: header('Access-Control-Allow-Origin: http://example.org'); header('Access-Control-Max-Age: 3628800'); heade ...

Is it possible to make the home page of a Next.js app in a subfolder with basePath accessible outside of the basePath?

My Next.js application is running in the '/portal/' folder and basePath has been configured as: module.exports = { basePath: '/portal' } Now, I want the index page of the application to be accessible at the site root (without baseP ...

Concentrate on the current Selenium screen for optimal performance

I'm currently using selenium in Python to test the functionality of a webpage that I'm developing. One issue I've encountered is that there are multiple instances where ids/names are repeated on the page. For example: <input class="" ...

Utilizing the Aladin Lite application within a React application, despite not being specifically designed for React

I am interested in incorporating the Aladin Lite app into my React application. Typically, embedding the app in a div is straightforward when developing a website without React: <!-- include Aladin Lite CSS file in the head section of your page --> ...

What is the reasoning behind declaring certain variables on the same line as others, while most are declared individually on separate lines?

I've taken on the challenge of learning JS by myself and decided to build a Blackjack game. While following a helpful walkthrough online, I encountered some confusion. On the website, they start by declaring Global variables: var deck; var burnCard; ...

When an HTML element is deleted, its events are not being removed as expected

I currently have events bound in my backbone view. sampleView = Backbone.View.extend({ events: { "click .sum": "sumButtonFunc", "click .diff": "diffButtonFunc" } sumButtonFunc: function(){ console.log("sum called") ...