views:

67

answers:

5

Hi,

Facing some problems with jQuery selectors.

My HTML is like:

<form method="" action="">  
    <p id="question_1">  
        <h1 id="question">1. A Question</h1>  
        <div id="choices">  
            <p id="option1"><input type="radio" id="option" name="q_1" value="1" />A</p>  
            <p id="option2"><input type="radio" id="option" name="q_2" value="2" />B</p>  
            <p id="option3"><input type="radio" id="option" name="q_3" value="3" />C</p>              
        </div>  
    </p>      
.  
.  
.  
</form>

There are n such questions.

I want to highlight the <p> containing the 3rd radio button for each question. For example,

    p#question_1 > p#option3  
    p#question_2 > p#option3  
    p#question_3 > p#option3  

How to do that?

I was trying something like this, without any success:

$("form p#question_" + i).filter("p:eq(3)").addClass("correct");
+1  A: 

I want to highlight the <p> containing the 3rd radio button for each question.

Use start with ^ selector with nth-child like this:

$('p[id^="question"]:nth-child(3)').addClass('correct');

What ^="question" does is that it selects all paragraphs starting with question text in their ids and then nth-child(3) is used to select the third paragraph.

More Info:

Sarfraz
A: 

There are many ways of doing that, here is a nice jQuery selectors refcard that will be very useful for you in the future.

http://refcardz.dzone.com/refcardz/jquery-selectors

StudiousJoseph
+1  A: 

If your third answer is always correct, you might opt for something like this instead:

<p class="first">Blah blah</p>
<p class="second">Blah blah</p>
<p class="third">Blah blah</p>

Then simply:

$("p.third").addClass("correct");

That should hopefully tempt you to get rid of those dupe IDs.

karim79
A: 

Would it be possible to just add a class to the third option for each question?

wshato
+1  A: 

I assume you want this to work if you have many div's with answers in them? Decorate each such div with DivChoices, and then:

$(".DivChoices").each(function (index, item) { $("p", item).last().addClass('correct'); });
Adam