Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
Is there a simpler way to check radio buttons?

I'm new to coding and learning HTML as well as JavaScript. I wrote a set of radio buttons in HTML so that you could toggle an option and click the submit button, and it would use JS to display the option you chose below. The code works fine, however:

  1. The code is quite clunky, I'm positive there must be a much more effective way of writing this code.
  2. I didn't use the form tag, should I? I'm still not entirely sure what form does other than I know it's used to collect data somehow

var x;

function displayText() {
  if (document.getElementById("lsd").checked === true) {
    x = document.getElementById("lsd").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("shrooms").checked === true) {
    x = document.getElementById("shrooms").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("dmt").checked === true) {
    x = document.getElementById("dmt").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("peyote").checked === true) {
    x = document.getElementById("peyote").value;
    document.getElementById("output").innerHTML = x;
  } else if (document.getElementById("toad").checked === true) {
    x = document.getElementById("toad").value;
    document.getElementById("output").innerHTML = x;
  }
}
<p>What's your preferred psychedelic substance?</p>
<input type="radio" id="lsd" name="drugs" value="lsd">
<label for="lsd">LSD</label>
<br>
<input type="radio" id="shrooms" name="drugs" value="shrooms">
<label for="shrooms">Magic Mushrooms/psilocybin</label>
<br>
<input type="radio" id="dmt" name="drugs" value="dmt">
<label for="dmt">DMT</label>
<br>
<input type="radio" id="peyote" name="drugs" value="peyote">
<label for="peyote">Peyote</label>
<br>
<input type="radio" id="toad" name="drugs" value="toad">
<label for="toad">The Toad/5-MeO-DMT</label>
<br>
<button onclick="displayText()">Submit!</button>
<p>
  User's favorite drug is: <span id="output"></span>
</p>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

A more powerful selector can select the element you want without manually checking each

function displayText() {
  const selected = document.querySelector("[name='drugs']:checked");
   
  const value = selected ? selected.value :null;

  document.getElementById("output").innerText = value;
}
<p>What's your preferred psychedelic substance?</p>
<input type="radio" id="lsd" name="drugs" value="lsd">
<label for="lsd">LSD</label>
<br>
<input type="radio" id="shrooms" name="drugs" value="shrooms">
<label for="shrooms">Magic Mushrooms/psilocybin</label>
<br>
<input type="radio" id="dmt" name="drugs" value="dmt">
<label for="dmt">DMT</label>
<br>
<input type="radio" id="peyote" name="drugs" value="peyote">
<label for="peyote">Peyote</label>
<br>
<input type="radio" id="toad" name="drugs" value="toad">
<label for="toad">The Toad/5-MeO-DMT</label>
<br>
<button onclick="displayText()">Submit!</button>
<p>
  User's favorite drug is: <span id="output"></span>
</p>

about 4 years ago · Juan Pablo Isaza Relatório

0

You can simplify it like this: You can paste it directly in HTML file and test. I would not recommend this for prod but for learning purposes it is good.

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
        name="viewport">
  <meta content="ie=edge" http-equiv="X-UA-Compatible">
  <title>Document</title>
</head>
<body>
<p>What's your preferred psychedelic substance?</p>
<form id="form">

</form>

<button onclick="displayText()">Submit!</button>
<p>
  User's favorite drug is: <span id="output"></span>
</p>
</body>
<script>
  const drugs = {
    "lsd": "LSD",
    "shrooms": "Magic Mushrooms/psilocybin",
    "dmt": "DMT",
    "peyote": "Peyote",
    "toad": "The Toad/5-MeO-DMT"
  };

  const form = document.getElementById("form");
  for (const key in drugs) {
    form.innerHTML += `
  <label style="display: block" for="lsd">
    <input type="radio" id="${key}" name="drugs" value="${key}">
    ${drugs[key]}
  </label>`;
  }

  function displayText() {
    const drugs = document.getElementsByName("drugs");
    for (let i = 0; i < drugs.length; i++) {
      if (drugs[i].checked) {
        document.getElementById("output").innerHTML = drugs[i].value;
      }
    }
  }
</script>
</html>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda