Input with multiple HTML values

Asked

Viewed 532 times

1

Well, my question is the following would it be possible for me to have a radio input with for example the values:

Portugal Spain France Brazil, Germany

And the person being able to select 2 options, that is when he switched to PHP had 2 values?

Thank you

  • 1

    search for checkbox

1 answer

2


You can achieve the desired using the element input type='checkbox'

JS code taken from here: https://stackoverflow.com/a/17422484

function teste() {
  var choices = [];
  var els = document.getElementsByName('check');
  for (var i = 0; i < els.length; i++) {
    if (els[i].checked) {
      choices.push(els[i].value);
    }
  }
  alert(choices);
}
<input type="checkbox" value="Brasil" name="check">Brasil
<br/>
<input type="checkbox" value="Portugal" name="check">Portugal
<br/>
<input type="checkbox" value="Espanha" name="check">Espanha
<br/>
<input type="checkbox" value="França" name="check">França
<br/>
<input type="checkbox" value="Alemanha" name="check">Alemanha
<br/>
<input type="button" value="checar" onclick="teste()">

Explaining line by line what the code does:inserir a descrição da imagem aqui


With that requirement of AT LEAST 2 SELECTED FIELDS AND AT MOST 2 SELECTED FIELDS you can * do so:

  • There are other means, perhaps even simpler....

function teste() {
  var choices = [];
  var els = document.getElementsByName('check');
  for (var i = 0; i < els.length; i++) {
    if (els[i].checked) {
      choices.push(els[i].value);
    }
  }
  if (choices.length <= 1 || choices.length > 2) {
    alert(`necessario 2 campos selecionados`);
  }else{
    alert(`ok, window.submit();`);
  }
  alert(choices);
}
    <input type="checkbox" value="Brasil" name="check">Brasil
    <br/>
    <input type="checkbox" value="Portugal" name="check">Portugal
    <br/>
    <input type="checkbox" value="Espanha" name="check">Espanha
    <br/>
    <input type="checkbox" value="França" name="check">França
    <br/>
    <input type="checkbox" value="Alemanha" name="check">Alemanha
    <br/>
    <input type="button" value="checar" onclick="teste()">

Browser other questions tagged

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