how to select more than one option in select Multiple using javascript?

Asked

Viewed 79 times

-2

I want to make the function seleciona( ), by clicking the Select button, select two of the options below. However, when I try to do this it selects only one option.

<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php">
  <label for="cars">Escolha uma ou mais cores:</label>
  <select name="cores" multiple readonly>
    <option value="1">Amarelo</option>
    <option value="2">Vermelho</option>
    <option value="3">Verde</option>
    <option value="4">Azul</option>
  </select>
  <br><br>
  <button type="button" onclick="seleciona()">selecionar</button>
</form>

<script>
function seleciona(){
    document.getElementsByName("cores")[0].value = 2,3;
}
</script>
</body>
</html>

2 answers

0


To do this you will have to pick up the specific elements using document.getElementsByName("cores")[0].getElementsByTagName('option') or document.querySelectorAll('select[name=cores] option')

Then you will have to iterate in loop, because both functions return "lists" of elements, in case will return the options, in DOM the property to "mark" an OPTION element as selected is the <elemento>.selected=true to unmark is <elemento>.selected=false

In case you want the Options with value=2 and value=3 to be selected, then just check in each element if they are the values you want:

var opcoes = document.getElementsByName("cores")[0].getElementsByTagName('option');

// poderia ser também
// var opcoes = document.querySelectorAll('select[name=cores] option');

function seleciona()
{
    for (var i = 0, j = opcoes.length; i < j; i++) {
        if (opcoes[i].value == "2" || opcoes[i].value == "3") {
            opcoes[i].selected = true;
        } else {
            opcoes[i].selected = false;
        }
    }
}
    <form action="/action_page.php">
      <label for="cars">Escolha uma ou mais cores:</label>
      <select name="cores" multiple readonly>
        <option value="1">Amarelo</option>
        <option value="2">Vermelho</option>
        <option value="3">Verde</option>
        <option value="4">Azul</option>
      </select>
      <br><br>
      <button type="button" onclick="seleciona()">selecionar</button>
    </form>

Note that I did it very explicitly and using if only to explain (to make it easy to understand the logic), but you can make it simpler like this:

for (var i = 0, j = opcoes.length; i < j; i++) {
    opcoes[i].selected = opcoes[i].value == "2" || opcoes[i].value == "3";
}

If it is 2 or 3 true arrow, otherwise false arrow

Now if you have specific values coming from another source you can use you can put them in an array to say that these should be the values marked, thus:

var valoresDeOutraFonte = [2, 3];

for (var i = 0, j = opcoes.length; i < j; i++) {
    opcoes[i].selected = valoresDeOutraFonte.indexOf(opcoes[i].value) !== -1;
}

The .indexOf() fetch on array valoresDeOutraFonte the current option value in the loop, if it is present returns 0 or a larger number, if it is not present returns -1. There is also the function .includes(), could do so:

var valoresDeOutraFonte = [2, 3];

for (var i = 0, j = opcoes.length; i < j; i++) {
    opcoes[i].selected = valoresDeOutraFonte.includes(opcoes[i].value);
}

But if you need to run on older browsers, as an old Android is likely to include no support

-3

You need to make a for going through the options and checking if they were selected.

    <!DOCTYPE html>
    <html>
    <body>
    <form action="/action_page.php">
      <label for="cars">Escolha uma ou mais cores:</label>
      <select name="cores" multiple readonly>
        <option value="1">Amarelo</option>
        <option value="2">Vermelho</option>
        <option value="3">Verde</option>
        <option value="4">Azul</option>
      </select>
      <br><br>
      <button type="button" onclick="seleciona()">selecionar</button>
    </form>


    <script>
    function seleciona() {
      let select = document.getElementsByName('cores')[0];
      let resultado = [];
      let opcoesDisponiveis = select && select.options;
      let opcao;

      for (let i=0; i<opcoesDisponiveis.length; i++) {
        opcao = opcoesDisponiveis[i];

        if (opcao.selected) {
          resultado.push(opcao.value || opcao.text);
        }
      }
      console.log(resultado);
    }
    </script>

    </body>
    </html>

Browser other questions tagged

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