2

I'm trying to first clear the class of all options and then add a class to the option with the corresponding letter. Here's my function:

function setAnswer(b, c){
      $('#'+b+' .option').removeClass("answer");
      $('#'+b+' .option'+c).addClass("answer");  
  }

and the form

 <div id="belh" class="options">
                <label>a.</label><input class="option optiona"><input onClick="setAnswer(this.parentnode.id, this.classname)" type="radio" class="a" name="answer">&nbsp;
                <label>b.</label><input class="option optionb"><input onClick="setAnswer(this.parentnode.id, this.classname)" type="radio" class="b" name="answer">
                <div class="clear"></div>
                <label>c.</label><input class="option optionc"><input onClick="setAnswer(this.parentnode.id, this.classname)" type="radio" class="c" name="answer">&nbsp;
                <label>d.</label><input class="option optiond"><input onClick="setAnswer(this.parentnode.id, this.classname)" type="radio" class="d" name="answer">
                </div>

the id for the div belh changes dynamically so I pass this.parentnode.id onto variable b in the function so i can do this:

 $('#'+b+' .option').removeClass("answer");

remove class from all option elements
now i pass this.classname to c so i can get the letter (a,b,c,d) to use here:

$('#'+b+' .option'+c).addClass("answer");

so that if the radio box with class c is clicked, all fields with class option within the div belh will lose the class answer, if they have it. then the field with class optionc will have class answer added to it. (because: $('#'+b+' .option'+c).addClass("answer");). For some reason my function isn't working. I think I'm passing the variables in the wrong way.

Atom Vayalinkal
  • 2,642
  • 7
  • 29
  • 37

2 Answers2

3

You should code this.className and this.parentNode.id, you can also use jQuery change event method and prev method for selecting previous sibling of the clicked input:

$('#belh input[name=answer]').change(function(){
    $('input.option').removeClass('answer');
    $(this).prev().addClass('answer')
})
Ram
  • 143,282
  • 16
  • 168
  • 197
1

Do you have tried toggle the class name? http://api.jquery.com/toggleClass/

gzfrancisco
  • 812
  • 10
  • 14