I have three radio inputs and I want to let the radio inputs return the value of the inputs uand execute a function when user selects one option.
Here is the code:
console.log(document.querySelector('input[name="radios"]:checked').value);
<form>
<input type="radio" id='HTML'name="radios" value="HTML">HTML<br>
<input type="radio" id="css" name="radios" value="CSS">CSS<br>
<input type="radio" id="javascript" name="radios" value="JavaScript">Javascript<br>
</form>
Thanks for the answer from Parthik Gosar, I could get the value from radio input.
But the problem is document.querySelector('input[name="radios"]:checked').value will get the value from the radio input once the page loaded which is null.
I just wonder is there some built-in function similar to onclick where it will execute a function when user select an option or other ways to solve the problem?
Thanks for any responds!
*I know we could use document.getElementById('').checked to check, but it will execute the function when the page loaded which will not work for me.,
>Solution :
You are looking for a click listener. Just attach one listener to the form element (event delegation allows you to add a listener to a parent element and capture events from child elements as they "bubble up" the DOM), and pick up the value of the clicked button and log it.
const form = document.querySelector('form');
form.addEventListener('click', handleClick, false);
// Because you're using event delegation the parent
// will watch for _all_ events from its children.
// So if you only want to watch for events from
// just the input buttons you need to grab the nodeName
// of the clicked element and then check to see if
// it's an input button before you do anything else
function handleClick(e) {
const { nodeName, value } = e.target;
if (nodeName === 'INPUT') {
console.log(value);
}
}
<form>
<input type="radio" id='HTML' name="radios" value="HTML">HTML<br>
<input type="radio" id="css" name="radios" value="CSS">CSS<br>
<input type="radio" id="javascript" name="radios" value="JavaScript">Javascript<br>
</form>