简体   繁体   中英

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();") />

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.

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()" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM