Put the options of an input select in a variable

Asked

Viewed 2,135 times

1

Good night.

It is possible in a select Multiple I save the chosen options in a variable and keep the chosen options?

Example:

<form class="form-inline">
<select id="opcoes" multiple name=opcoes[] >
        <option value="1">Option1</option>
        <option value="2">Option2</option>
        <option value="3">Option3</option>
    </select>
      <button type="submit" class="btn btn-default">Enviar</button>

</form>

If yes, how can I retrieve it and reuse in the same select?

  • Excuse me, but $("#opcoes").val() no longer returns the list of selected values? What do you mean about "saving to a variable and keeping the chosen options"?

  • Possible! Try to get the value in the change event. As the field is multiple, an array will be returned.

3 answers

2

So, <select multiple /> has an attribute called selectedOptions that returns the <option /> chosen. Then just go through them at the event onChange same. With pure Javascript gets like this:

var selecionadas = [];
var opcoes = document.querySelector('#opcoes');
opcoes.addEventListener('change',    function(ev){
   var selectedOptions = ev.target.selectedOptions;
   selecionadas = [];
   for (var i = 0; i < selectedOptions.length; i++){
      selecionadas.push(selectedOptions[i].value);
   }
   console.log(selecionadas);
});
<form class="form-inline">
<select id="opcoes" multiple name=opcoes[] >
        <option value="1">Option1</option>
        <option value="2">Option2</option>
        <option value="3">Option3</option>
    </select>
      <button type="submit" class="btn btn-default">Enviar</button>

</form>

  • Why don’t you just use $("#opcoes").val() to recover the selected values?

  • Good question! I don’t know, I’ll change.

  • 1

    Although the others already use it, so leave that as a different answer anyway. You won’t always get jQuery, so it’s good to know how it’s done in pure JS.

  • 1

    Yeah, that’s for sure. So maybe, to increase "the beauty" of the answer, you could implement it all with pure JS, since the only jQuery tool you use is just the function on and could easily be replaced by addEventListener.

  • Thanks for the tip @Andersoncarloswoss !

  • @Daniel a contracted form would be.: var selecionados = [].slice.call(e.target.selectedOptions).map(o => o.value))

  • @Tobiasmesquita I don’t know if it’s worth so much to contract code that way, unless you’re trying to get high performance, in my opinion it’s best to keep the code well readable. I really should use the method map however, instead of a for, that looks better to read too.

Show 2 more comments

0

It is possible yes, even more using Jquery, there are several ways, if I am not mistaken Oce can bind an event for example: "onClick" in the options and then when the user clicks you perform a function that adds or removes this value in the array, in case the value of the option you passing the option as argument could take so: $(option).val(); to pass the option as argument you can do so

<option value="1" onClick="adicionarNoArray(this)">Option1</option>

I’m sorry about "If I’m not mistaken", I haven’t touched jQuery in a while, but I’m going to test it and then post a comment here saying whether it worked or not.

EDIT

<html>
        <head>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        </head>

        <body>
                <select id="select" multiple>
                        <option value="1" onClick="adicionarArray(this)">Option1</option>
                        <option value="2" onClick="adicionarArray(this)">Option1</option>
                        <option value="3" onClick="adicionarArray(this)">Option1</option>
                </select>

        <script>
                var valores = [];
                function adicionarArray(option)
                {
                        var index = valores.indexOf($(option).val());
                        if(index != -1)
                        {
                                valores.splice(index, 1);
                        }
                        else
                        {
                                valores.push($(option).val());
                        }
                                console.log(valores);
                }
        </script>
        <body>
</html>

That should solve your problem. Maybe this is not the best way to do it and another can come with a better answer, but this way you can put the values as they are selected in an array and work with the values.

0

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
  <title>Resposta</title>
</head>
<body>
  <select id="opcoes" multiple name="opcoes">
    <option value="1" class="selecionar">Option1</option>
    <option value="2" class="selecionar">Option2</option>
    <option value="3" class="selecionar">Option3</option>
  </select>

</body>

<script>
  opcoes = []
  $(".selecionar").click(function(e){
    $('#opcoes :selected').each(function(i, selecionado){
      if($.inArray(selecionado,opcoes) == -1){
        opcoes.push(selecionado);
      }else{
        opcoes.splice(i,1);
      }
    });
    console.log(opcoes);
  });
</script>
</html>
  • Why don’t you just use $("#opcoes").val() to recover the selected values?

Browser other questions tagged

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