Javascript Vanilla - Take select value Multiple and mount in json

Asked

Viewed 210 times

1

<button id="get">Estilos</button>

<select id="estilos-select" multiple>
  <option value="1">Sertanejo</option>
  <option value="2">MPB</option>
  <option value="3">Samba</option>
  <option value="4">Pagode</option>
</select>

I have the select multiple choice, in which I need to take the values and mount a json. With jQuery I do the following:

$("#get").click(function(){
    let data = {};
    data['id_estilo'] = JSON.stringify($('#estilos-select').val())
    console.log(JSON.stringify(data))
})

And the result is {"id_style":"[ "1 ", "2\"]"}

How do I get the same result with pure javascript? I know you need to put in a for, but how do I array inside the "id_style key"?

let data = {}
for (let i=0; i<estilos.length; i++){
    data.id_estilo['id_estilo'] = estilos[i].value
}

That line, for example, doesn’t work, or even if I do data.id_estilo['id_estilo'].push(estilos[i].value)

  • but if you are using jquery it is not vanilla javascript :)

  • Precisely, I need to translate this code to pure js

1 answer

2


The simple example with vanilla is to make a loop in the options of select and check which items are selected, example:

var button = document.getElementById("get");
button.addEventListener("click", function() {
  var select = document.getElementById("estilos-select");
  var items = [];
  for(let i = 0; i < select.options.length; i++)
  {
    if (select.options[i].selected)
    {
      items.push(select.options[i].value);
    }
  }
  obj = { id_estilo: items };
  console.log(obj);
});
<button id="get">Estilos</button>

<select id="estilos-select" multiple>
  <option value="1">Sertanejo</option>
  <option value="2">MPB</option>
  <option value="3">Samba</option>
  <option value="4">Pagode</option>
</select>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.