Html "Double" Select required

Asked

Viewed 81 times

0

Hello, I’m trying to make a form in html where it contains TWO selects required, but I will use only one at a time, ie when I select one the other required should pass "beaten". The structure is as follows:

<form>
  <select required>//se esse for selecionado não precisaria selecionar o outro
    <option value="">
    <option value="1">1</option>
    <option value="2">2</option>
  </select>
  <select required>//da mesma forma se esse for selecionado o outro não precisa ser também.
    <option value="3">3</option>
    <option value="4">4</option>
  </select>
</form>

The result of this code does not let me select only 1 select, I must select both for it to work, ie I would like a structure in the logic style "OR" and not "AND" as occurs here. If you have any way to do it without JS would be even better.

NOTE: Yes I need two SELECTS to do this for intuitive reasons.

1 answer

1


The only solution I know is through Javascript.

I created a method that will run every time one of your select is changed, it will receive the id and the value of elemento altered.

If the elemento changed then have value the other select will lose its obligation.

Follows example working:

function removeObrigatoriedade(id, valor){
  var lista1 = document.getElementById("lista1");
  var lista2 = document.getElementById("lista2");
  
  if(id=="lista1" && valor != ""){
    lista1.required = true;
    lista2.required = false;
  }
  
  if(id=="lista2" && valor != ""){
    lista2.required = true;
    lista1.required = false;
  }
  
}
<form action="#">
  <select name="lista1" id="lista1" required onchange="removeObrigatoriedade(this.id, this.value)">
    <option value="">
    <option value="1">1</option>
    <option value="2">2</option>
  </select>
  <select name="lista2" id="lista2" required onchange="removeObrigatoriedade(this.id, this.value)">
    <option value="">
    <option value="3">3</option>
    <option value="4">4</option>
  </select>
  
  
  <button type="submit" name="enviar" id="enviar">Enivar</button>
</form>

  • Was exactly that, thank you only problem of JS is that we really do not always have support for it unfortunately.

  • I understand your situation, I’m glad I helped you :)

Browser other questions tagged

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