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

163
Visualizações
Return value from on an onclick radio button

Trying to return a value from a function based on radio input however I keep getting either a null or

Uncaught TypeError: Cannot read properties of null (reading 'value')".

function myFunction() {
  var radioTest = document.querySelector('input[name="inputtest"]:checked').value;
  return radioTest;
}

var test = myFunction();
console.log(test);
<input type="radio" id="test123" name="inputtest" value="testing 123" onclick( "myFunction();") />

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

0

When the page is loaded, there is no checked input. To make it work for both page load and input checked, you can use Optional Chain for the assertion.

Also, the syntax is invalid. Instead of

onclick( "myFunction();")

use

onclick="myFunction()"

Here is the full code

function myFunction() {
  var radioTest = document.querySelector('input[name="inputtest"]:checked')?.value;
  console.log(radioTest);
  return radioTest;
}

var test = myFunction();
<input type="radio" id="test123" name="inputtest" value="testing 123" onclick="myFunction()" />

A note: I'd recommend to use onchange in case you have more than one radio button in your form.

about 4 years ago · Juan Pablo Isaza Relatório

0

There are two issues in your code.

  1. The way you are attaching the click event.
  2. You are calling myFunction() on load. So it is throwing an exception because raiobutton is not checked.

Use the below code.

function myFunction() {
  var radioTest = document.querySelector('input[name="inputtest"]:checked').value;
  return radioTest;
}

function handleClick()
{
  let radioValue = myFunction();
  console.log(radioValue);
}
<input type="radio" id="test123" name="inputtest" value="testing 123" onclick = "handleClick()" />

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