Home > Software design >  JS Radio botton getting ON instead of value
JS Radio botton getting ON instead of value

Time:12-03

let apples = ['Fuji','Gala','Braeburn'];
const basketDiv = document.getElementById('basket');


for (const apple of apples) {
  let radiobtn= document.createElement('input');
  radiobtn.setAttribute('type', 'radio');
  let radiolabel = document.createElement('label');
  radiolabel.innerHTML= apple;
  radiobtn.name= 'apples';
  radiobtn.id= apple;
  basketDiv.append(radiobtn);
  basketDiv.append(radiolabel);
  radiobtn.addEventListener('change',message);
}



function message(e) {
  let getselected = getSelectedValue = document.querySelector('input[name="apples"]:checked'); 
    if(getselected != null) { 
                document.getElementById("show").innerHTML= getselected.value   "  is selected"; 
            } 
            else { 
                document.getElementById("show").innerHTML = "*You have not selected  "; 
            } 
  }
  

i should get apple values but i couldn't It gives me ON , i don't know what ON is i need to know what is my mistake

CodePudding user response:

It looks like there are a couple of mistakes in your code. In the message() function, you are trying to get the value of the selected radio button using getselected.value. However, the value property of a radio button is only set if you explicitly give it a value. Since you haven't given any of your radio buttons a value, getselected.value will always be undefined.

To fix this, you can set the value attribute of each radio button to the corresponding apple name using the setAttribute() method. Then, in the message() function, you can use the id property of the selected radio button instead of its value property to get the name of the selected apple.

Here's how you can fix the code:

let apples = ['Fuji','Gala','Braeburn'];
const basketDiv = document.getElementById('basket');


for (const apple of apples) {
  let radiobtn= document.createElement('input');
  radiobtn.setAttribute('type', 'radio');
  let radiolabel = document.createElement('label');
  radiolabel.innerHTML= apple;
  radiobtn.name= 'apples';
  radiobtn.id= apple;
  radiobtn.value = apple;  // Set the value attribute of the radio button to the apple name
  basketDiv.append(radiobtn);
  basketDiv.append(radiolabel);
  radiobtn.addEventListener('change',message);
}



function message(e) {
  let getselected = getSelectedValue = document.querySelector('input[name="apples"]:checked'); 
  if(getselected != null) { 
    // Use the id property of the selected radio button to get the apple name
    document.getElementById("show").innerHTML= getselected.id   "  is selected"; 
  } else { 
    document.getElementById("show").innerHTML = "*You have not selected  "; 
  } 
}

I hope this helps.

  • Related