Evgeniy
Evgeniy

Reputation: 2595

How to transfer selected values from select element to javascript?

i have a select element with multiple selection, like this:

<select multiple>
  <option value="en">English</option>
  <option value="de">German</option>
</select>

And i have a javascript, which should use selected values, looking like:

$.ajax({
                url: window.location.protocol + "//example.com/search",
                jsonp: "jsonp",
                dataType: "jsonp",
                data: {
                q: querykeyword,
                client: "chrome",
                hl: "HERE SHOULD APPEAR ONE OR TWO SELECTED VALUES"
                }

So the last code line should look like hl: "en" or, hl: "de", or hl: ["en","de"].

How can i transfer values from select element into javascript?

Upvotes: 2

Views: 495

Answers (2)

wangdev87
wangdev87

Reputation: 8751

Use selectedOptions property.

var selectedOptions = document.querySelector("select").selectedOptions;
var values = [];
for (let i=0; i<selectedOptions.length; i++) {
  values.push(selectedOptions[i].value);
}

.value will not work, as it will show only one selected option.

console.log(document.querySelector("select").value)
<select multiple>
  <option value="volvo" selected>Volvo</option>
  <option value="saab" selected>Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

Upvotes: 2

Or Assayag
Or Assayag

Reputation: 6336

You need to take the selected value from the select element. You can do that by: document.querySelector("select").value, so the full solution for your code will be:

$.ajax({
      url: window.location.protocol + "//example.com/search",
      jsonp: "jsonp",
      dataType: "jsonp",
      data: {
        q: querykeyword,
        client: "chrome",
        hl: document.querySelector("select").value
      });

Upvotes: 0

Related Questions