the scenario is that i want to set the total price based on user choice of radio buttons, when user chooses one of the radio buttons the price changes accordingly.
here is the the HTML:
<div >
<h4 style="text-align: center;">إختر الباقة</h4>
<input type="radio" name="package" id="pk1" value="70">
<label for="pk1">بالساعة</label>
<input type="radio" name="package" id="pk2" value="200">
<label for="pk2">يوم</label>
<input type="radio" name="package" id="pk3" value="2500">
<label for="pk3">شهر</label>
</div>
<div >
<input type="number" placeholder="Total Value" name="price" id="output">
<i aria-hidden="true"></i>
</div>
i tried to use javaScript solution such as:
<script>
document.getElementsByName("package").addEventListener("change", function(){
document.getElementById("output").innerHTML = this.value;// Show the value in output element
});
</script>
but it seems nothing works for me, i appreciate any help, Thank you :)
CodePudding user response:
There's a couple of issues with your code to start with. If you check in the browser console you will see errors and specific line numbers where they occurred - that's always a good place to start.
First, getElementsByName
returns a collection of elements, so you need to loop over it and attach event listeners one by one. You can't just call addEventListener
to apply them all at once like you do with jquery, for example. Take a look at the documentation for that function here: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName
Second, you're trying to update the output
element by setting its innerHTML
, but that element is a number input. You need to update its value
property instead.
Here's a snippet bringing all that together.
const radios = document.getElementsByName('package')
radios.forEach(function(radio) {
radio.addEventListener('change', function() {
document.getElementById("output").value = this.value;
})
})
<div >
<h4 style="text-align: center;">إختر الباقة</h4>
<input type="radio" name="package" id="pk1" value="70">
<label for="pk1">بالساعة</label>
<input type="radio" name="package" id="pk2" value="200">
<label for="pk2">يوم</label>
<input type="radio" name="package" id="pk3" value="2500">
<label for="pk3">شهر</label>
</div>
<div >
<input type="number" placeholder="Total Value" name="price" id="output">
<i aria-hidden="true"></i>
</div>