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.

2
  • I think you're complicating things too much... Why this $('#'+b') and not $('.options')? Commented Oct 7, 2012 at 20:36
  • because the div (parent to the radio button) is duplicated over and over with different ids and same class. Commented Oct 7, 2012 at 20:40

2 Answers 2

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') }) 
Sign up to request clarification or add additional context in comments.

3 Comments

what do you mean by "code this.classname", is it just the capital N? sorry noob question.
@theatomicdude Yes, the name of the property is className and the other one parentNode.
wow. Unbelievably, that actually worked (the capitalization), i did not know that mattered.
1

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

1 Comment

the accepted answer worked for me, but this looks like a great idea as well. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.