Issue
I only did this code of Javascript
so maybe I need to do an add an event listener
but i don't know what I need to do
pick_up:document.getElementById("shippingOption1").value,
delivery:document.getElementById("shippingOption2").value
The output is:
pick up:onor
delivery:on
I want so that one of them be on if checked and off if its not checked how can i do that?
HTML:
<div class="custom-control custom-radio">
<input id="shippingOption2" name="shipping-option" class="custom-control-input" type="radio">
<div class="custom-control custom-radio"><input id="shippingOption1" name="shipping-option" class="custom-control-input" checked="checked" type="radio" ">
<label class="custom-control-label" for="shippingOption1">
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
Solution
In order to see if a radio button is selected or not, you should use the .checked
attribute.
pick_up: document.getElementById("shippingOption1").checked,
delivery: document.getElementById("shippingOption2").checked
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:
function handleChange() {
const options = {
pick_up: document.getElementById("shippingOption1").checked,
delivery: document.getElementById("shippingOption2").checked
}
const result = document.querySelector('.result');
if (options.pick_up) {
result.textContent = 'You chose pickup';
} else if(options.delivery) {
result.textContent = 'You chose delivery';
}
console.log(options);
};
<div class="custom-control custom-radio">
<input id="shippingOption2" name="shipping-option" class="custom-control-input" type="radio" onchange="handleChange()" value="delivery">
<label class="custom-control-label" for="shippingOption2">delivery</label>
</div>
<div class="custom-control custom-radio">
<input id="shippingOption1" name="shipping-option" class="custom-control-input" type="radio" onchange="handleChange()" value="pick_up">
<label class="custom-control-label" for="shippingOption1">pick_up</label>
</div>
<div class="result">Select an option</div>
<div class="result2">The value of the selected option is: </div>
Answered By - Marin Bînzari
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.