I only did this code of java script
so maybe I need to do an add event listener but i don’t know what I need to do
JavaScript
x
3
1
pick_up:document.getElementById("shippingOption1").value,
2
delivery:document.getElementById("shippingOption2").value
3
JavaScript
1
5
1
the output is
2
pick up:onor
3
4
delivery:on
5
i want so that one of them be on if checked and off if its not checked how can i do that?
html
JavaScript
1
6
1
<div class="custom-control custom-radio">
2
<input id="shippingOption2" name="shipping-option" class="custom-control-input" type="radio">
3
4
<div class="custom-control custom-radio"><input id="shippingOption1" name="shipping-option" class="custom-control-input" checked="checked" type="radio" ">
5
<label class="custom-control-label" for="shippingOption1">
6
ps I already tried adding value of 1 and 2 to html code but it only gives 1 and 2 regardless that its not checked
Advertisement
Answer
In order to see if a radio button is selected or not, you should use the .checked
attribute.
JavaScript
1
3
1
pick_up: document.getElementById("shippingOption1").checked,
2
delivery: document.getElementById("shippingOption2").checked
3
For value, you could add the attribute value="delivery"
in order to know what is checked without knowing it’s id
.
Here’s a piece of code how it works:
JavaScript
1
16
16
1
function handleChange() {
2
const options = {
3
pick_up: document.getElementById("shippingOption1").checked,
4
delivery: document.getElementById("shippingOption2").checked
5
}
6
7
const result = document.querySelector('.result');
8
9
if (options.pick_up) {
10
result.textContent = 'You chose pickup';
11
} else if(options.delivery) {
12
result.textContent = 'You chose delivery';
13
}
14
15
console.log(options);
16
};
JavaScript
1
13
13
1
<div class="custom-control custom-radio">
2
<input id="shippingOption2" name="shipping-option" class="custom-control-input" type="radio" onchange="handleChange()" value="delivery">
3
<label class="custom-control-label" for="shippingOption2">delivery</label>
4
</div>
5
6
<div class="custom-control custom-radio">
7
<input id="shippingOption1" name="shipping-option" class="custom-control-input" type="radio" onchange="handleChange()" value="pick_up">
8
<label class="custom-control-label" for="shippingOption1">pick_up</label>
9
</div>
10
11
12
<div class="result">Select an option</div>
13
<div class="result2">The value of the selected option is: </div>