Pregunta

Anyone know how to loop through a group of radio buttons and remove ones that haven't been checked?

What I'm trying to do is set up a quiz to where once you've submitted the quiz it will only show you the answers to the radio buttons you selected...

Any help would be great appreciated!

Page I'm working on: http://adventures.org/quiz/default_post.asp

¿Fue útil?

Solución

If this is pure javascript, you would use something like:

var inputs = document.getElementById('myForm').getElementsByTagName('input'), 
    i = inputs.length - 1; //Loop backwards to avoid issues when removing an input 
    for(; i >= 0; i--) { //for loop
    //Is this an unchecked radio button
    if(inputs[i].type === 'radio' && !inputs[i].checked) {
        //Remove this input element
        inputs[i].parentNode.removeChild(inputs[i]);
    }
}

UPDATE

Per user's comment, it would appear that he is trying to remove the entire label element that contains the radio input. The below code will accomplish this.

var inputs = document.getElementsByTagName('input'), 
    i = inputs.length - 1, 
    item;
//Loop backwards through items
for(; i >= 0; i--) {
    //If this is an unchecked radio button
    if(inputs[i].type === 'radio' && !inputs[i].checked) {
        //Begin trying to find the label item
        item = inputs[i].parentNode;
        //Is this the label item
        while(item && item.nodeName.toLowerCase() !== 'label') {
            item = item.parentNode;
        }
        //If an item was found
        if(item && item.parentNode) {
            //Remove the label element
            item.parentNode.removeChild(item);
        }
    }
}

Otros consejos

You could do this:

var yourForm = document.getElementById("yourFormId");
var removeUnchecked = function (form) {
  var childrenList = form.children,
      num = childrenList.length - 1;
  for (var i = 0; i >= num; i--) {
    if (!childrenList[i].checked) {
      form.removeChild(childrenList[i]);
    }
  }
}

removeUnchecked(yourForm);

Replace the id in the first line with the id of your form element.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top