Skip to content

i receive the output value of radio buttons as both on even though one is checked

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

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

Answer

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>