Mike Mike - 1 year ago 85
Javascript Question

Using chrome.tabs.executeScript to populate multiple-select fields

I have looked on here for similar queries, but I'm struggling to find the answer I'm looking for.

I'm writing a very basic chrome extension, which will allow users to populate frequently used forms (basically there's one form that's huge, which users have to complete, but a lot of the information never changes).

The form itself isn't mine, so I can't edit it at all and it's set up 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>

I'm using the following to inject values into text fields, and that's not causing any problems:

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

The issue I'm having is there are a bunch of multiple select boxes on the form, and in cases where I only need to pre-fill one value, the above works fine. however, if I need to select multiple options it won't work.

I've tried various naive attempts 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"];

But of course none of these are working. in some cases it selects the first option, in other cases nothing at all.

I'd also rather not use jQuery if at all possible.

Answer Source

in case of multiple options select you need first to add (if they are not a multiple selects)

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

then you can do



document.querySelector('#SelectField option[value="Option1"]').selected = true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download