As there are multiple radios, you will want to loop through each radio, adding an event listener to them.
const prices = document.querySelector(".radio-price");
const priceRadios = prices.querySelectorAll("[type=radio]");
priceRadios.forEach(function (radio) {
radio.addEventListener("change", updatePriceHandler);
});
We usually use a handler function, so that it can retrieve the event information that’s useful, and pass it on to something else.
In the handler, we get the radio, and pass it to updatePrice.
function priceRadioHandler(evt) {
const radio = evt.target;
updatePrice(radio);
}
The updatePrice function is nice and easy to achieve:
function getInputFromRadio(radio) {
return radio.nextElementSibling;
}
function updatePrice(radio) {
const input = getInputFromRadio(radio);
document.querySelector("#price").innerHTML = input.value;
}
That works for when clicking on the radio buttons.
Next, we want an update to the inputs to update the price too. We can use the same getInputFromRadio function that we used before.
const priceInputs = Array.from(priceRadios).map(getInputFromRadio);
priceInputs.forEach(function (input) {
input.addEventListener("change", priceInputHandler);
});
The priceInputHandler gets the input element from the event information, and uses that to get the radio and pass it on to the updatePrice function.
function priceInputHandler(evt) {
const input = evt.target;
const radio = getRadioFromInput(input);
updatePrice(radio);
}
There is a problem though. You can select radio 2, and then update input 3 and the price updates to that third one. We don’t want that. Instead we want to search through for the selected radio element, and show only that price.
That means that the updatePrice function shouldn’t just get the input value. Instead it needs to use the radio element to get the selected radio button, and only show the value of that one.
function getCurrentRadio(radio) {
const form = radio.form;
const radios = form.elements[radio.name];
return Array.from(radios).find(function (radio) {
return radio.checked;
});
}
function updatePrice(radio) {
const currentRadio = getCurrentRadio(radio);
const input = getInputFromRadio(currentRadio);
document.querySelector("#price").innerHTML = input.value;
}
There’s an example page with the code in action at https://jsfiddle.net/owrg1bsa/
Try selecting a radio button, then a price input from a different line and see if that lines up with your expected behaviour.
To help avoid confusion, I’ve added a bit more so that when you click on a price field, it selects that radio too.
function priceClickHandler(evt) {
const input = evt.target;
const radio = getRadioFromInput(input);
radio.checked = true;
}
...
const priceInputs = Array.from(priceRadios).map(getInputFromRadio);
priceInputs.forEach(function (input) {
input.addEventListener("click", priceClickHandler);
input.addEventListener("change", priceInputHandler);
});
See if you like that variation better, at https://jsfiddle.net/owrg1bsa/1/