Leveraging chrome.tabs.executeScript for populating various select options in multi-select fields

Despite my efforts to find a solution on similar posts, I am still struggling to find the specific answer I need.

I am currently developing a simple chrome extension that aims to streamline the process of filling out a large form with static information. The form itself is fixed and cannot be edited, structured like this:

<select multiple="multiple" id="SelectField">
  <option value="Option 1">Option 1</Option>
  <option value="Option 2">Option 2</Option>
  <option value="Option 3">Option 3</Option>
</select>

Injecting values into text fields has been smooth sailing so far using this method:

document.getElementById("TextField").value = "Text Field Value";

The challenge arises when dealing with multiple select boxes on the form. While pre-filling one value works fine, attempting to select multiple options simultaneously does not. I have experimented with different approaches such as:

document.getElementById("SelectField").value = "Option 1","Option 3";
document.getElementById("SelectField").values = "Option 1","Option 3";
document.getElementById("SelectField").value = ["Option 1","Option 3"];
document.getElementById("SelectField").values = ["Option 1","Option 3"];

However, none of these methods seem to produce the desired outcome. At times, it only selects the first option, while in other instances nothing happens at all.

In addition, I would prefer to avoid using jQuery if possible.

Answer №1

If you have multiple options to select, the first step is to ensure that they are set up as multiple selects.

document.getElementById("SelectField").multiple = true;

Once that's done, you can proceed with selecting your options:

document.getElementById("SelectField").options[0].selected=true;
document.getElementById("SelectField").options[1].selected=true;

Alternatively, you can use:

document.querySelector('#SelectField option[value="Option1"]').selected = true

Answer №2

To handle <select multiple="true"> elements, you need to set the selected property on each individual <option> element.

One way to achieve this is as follows:

var optionsToSelect = ["Option 1","Option 3"];

optionsToSelect.forEach(option => {
    document.querySelector('#SelectField option[value="'+option+'"]').selected = true;
});
<select multiple="multiple" id="SelectField">
  <option value="Option 1">Option 1</Option>
  <option value="Option 2">Option 2</Option>
  <option value="Option 3">Option 3</Option>
</select>

When extracting this information from JSON data, it may involve selecting multiple elements and handling cases where the JSON includes options or IDs that do not currently exist. A more generic, efficient, and robust approach would be necessary in such scenarios. This can introduce a level of complexity:

var optionsToSelect = ["Option 1","Option 3"];

setMultipleOptionsById('SelectField',optionsToSelect);

function setMultipleOptionsById(id,selectedOptions) {
    let selectEl = document.getElementById(id);
    if(selectEl){
        selectedOptions.forEach(option => {
            let optionEl = selectEl.querySelector('option[value="'+option+'"]');
            if(optionEl) {
                optionEl.selected = true;
            }
        });
    }
}
<select multiple="multiple" id="SelectField">
  <option value="Option 1">Option 1</Option>
  <option value="Option 2">Option 2</Option>
  <option value="Option 3">Option 3</Option>
</select>

Currently, the function above simply disregards any missing <select> or <option> elements. To enhance it, you could easily incorporate a return value indicating any missing elements and providing details about them.

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 ngModel directive automatically clears the checkbox's Checked status

Currently, my Angular code is set up to validate a checkbox using ng-model: <input type="checkbox" name="news1" value="news1" ng-model="news" <c:if test="${xxxx == yes'}">checked="checked"></c:if>> <label ng-click="news1();"&g ...

An object rotating in a loop with Three.js will not cast a shadow over the entire scene

Why are some cubes in my loop not casting shadows? Despite using a directional light that should cast shadows on all cubes, the shadowing stops after around 5 columns. let dirLight = new THREE.DirectionalLight(0xFFFFFF, 1.5); dirLight.position.set(300, - ...

Just a Quick Query About Regular Expressions

I need help removing a specific part from a URL string, which looks like this: http://.....?page=1. I am aware that the code "document.URL.replace("?page=[0-9]", "")" does not work, so I am curious to learn how to accomplish this task correctly. Thank you ...

Tips for showcasing nested information on the web page

Attempting to retrieve data from an API and insert it into the DOM In this case, the data is in the form of an array containing objects. Here's a sample of what the API displays in the console. https://i.sstatic.net/MLKya.png To access the array w ...

Tips for refreshing only a portion of a webpage using JavaScript/jQuery

I have two distinct navigational sections on my website. The left column has its own navigation menu, while the right column (main content area) contains a separate set of links: My goal is to click on a link in the left-hand sidebar (such as "Resume", "E ...

Exploring Angular 4: Embracing the Power of Observables

I am currently working on a project that involves loading and selecting clients (not users, but more like customers). However, I have encountered an issue where I am unable to subscribe to the Observables being loaded in my component. Despite trying vario ...

Connect the mileage tracker to a Datalist or grid view component

I recently downloaded the Odometer Sample from , however, I am facing an issue where only the first element in the Datalist is getting the Odometer display, while others are not displaying it. Here is the snippet of code: <script type="text/javascript" ...

Issue with Angular controller failing to load when link is clicked

I am currently developing a webpage that incorporates Angular and responds to ajax requests by populating data into a table. When I manually enter the address, everything works as expected. However, if I navigate to the page using a link ( <a href="/pro ...

Can you pass a specific function as a parameter in express.post()?

I have a snippet of code that is functioning correctly. I am wondering if it is possible to pass a pre-defined function as a parameter within express.post(). const exs = require('express'); const exs_r = exs.Router(); router.post('/click&a ...

The Cy.visit() function in Cypress times out and bypasses tests specifically when navigating to a VueJS web application

Having trouble with the Cypress cy.visit() function timing out and aborting tests on a VueJS Web Application? It seems to work fine when opening other non-VueJS sites. Below is my basic configuration setup: [package.json] "dependencies": { "cypres ...

Display or Conceal form based on radio button selection of affirmative or negative

I'm experimenting with using jQuery to display more or less of a form depending on the user's selection. If the user chooses 'Yes,' then additional form fields will be shown. I intend to implement this feature for various top-level ques ...

Initial page load experiencing issues with paroller.js functionality

Upon hard refreshing the page in the middle section, there seems to be an issue with the paroller js transform: translateY(); CSS effect not functioning properly on the <div class="col col-6" data-paroller-factor="0.4" data-paroller-type="foreground" da ...

Listening to events on the iterative variable of NgFor directive in Angular 2

Angular2 has been my latest exploration in solving a unique data binding challenge. In my UI, I've presented a javascript array of objects like a database recordset in an HTML table. Each row contains menus and inputs allowing users to modify the rec ...

Obtaining the body from a post request in Node.js: A step-by-step guide

When sending data with the id using the post method to my node server, I encountered an issue where req.body is returning as undefined in my node file. This is what my index.html looks like: <html ng-app="IMDBApp"> <body> <div ng-contr ...

The XHR Get request fails to load the HTML content sent from the Express application

As I embark on building my inaugural express app, I have encountered a shift in sending requests from the front-end. Previously, all requests were initiated by anchor elements for GET requests and form elements for POST requests, with server responses hand ...

What is the process for integrating Socket io into an external JavaScript file that is connected to an HTML file?

Currently, I am utilizing node js, socket io, and express to develop a multiplayer web game. To begin, the server initiates and listens on port 2000. Upon visiting localhost:2000, the file lobby.html is transmitted using: //app.js const express = require ...

How can I switch between different images using jQuery?

HTML <div class="image_rollover"> <img id="image_one" src=image_one.png"> <img id="image_two" src="image_two.png"> <img id="image_three" src="image_three.png"> <img id="image_four" src="image_four.png"> ...

Issue with locating JavaScript controller in Angular HTML file [Node.js/Angular]

Here are all the files and folders in my project located within the same directory. If you want to check out the project on Github, you can find it here: https://github.com/JohnsCurry/learnAngular. Just to confirm, they are all in the same folder. Unfortu ...

Leveraging JavaScript's Document.write() function to generate an HTML hyperlink

I am struggling with a URL stored in a variable (var URL). My initial attempt was this: document.write("<a href='"+url+"'>LINK</a>"); Unfortunately, it is not working as expected. Any suggestions on how to fix this? This is the ex ...

AngularJS: default option not being selected in dropdown menus

I need assistance with a dropdown list issue. See the code snippet below: My Controller (function(angular) { 'use strict'; angular.module('ngrepeatSelect', []) .controller('ExampleController', ['$scope', functi ...