Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!