user1490145
user1490145

Reputation: 153

adding and removing class is not working correctly

I have a php code where it displays buttons from A-Z:

  <table id="optionAndAnswer" class="optionAndAnswer">
    <tr class="answer">
    <td>3. Answer</td>
    <td>
        <?php
            $a = range("A","Z");
        ?>

        <table id="answerSection">
            <tr>

        <?php
            $i = 1;
            foreach($a as $key => $val){
                if($i%7 == 1) echo"<tr><td>";
                echo"<input type=\"button\" onclick=\"btnclick(this);\" value=\"$val\" id=\"answer".$val."\" name=\"answer".$val."Name\" class=\"answerBtns answers answerBtnsOff\">";      
                if($i%7 == 0) echo"</td></tr>";
                $i++;
            }
        ?>

...

Now these buttons should turn on and turn off using ".answerBtnsOn" and ".answerBtnsOff"

The problem I have is that it highlights the buttons which should be turned on, but it doesn't unhighlight (turn off) the other buttons. So if button B was highlighted but now the answer is A and C, it should turn on only buttons A and C and all other buttons should be turned off but this doesn't happen as button B is still turned on along with A and C.

So my question is that how can I turn off the buttons that should turned off. At the moment it is turning on the correct buttons but not turning off the other buttons.

Below is current code:

var answers = $.map(btn.split(''),function(chr){   return "#answer"+chr;  }).join(', ');

        $(answers).removeClass('answerBtnsOn').addClass('answerBtnsOff');
        $(answers).addClass("answerBtnsOn").siblings().addClass('answerBtnsOff');

UPDATE:

Here is a DEMO so you can see what is happening, pease follow the steps below in order to use the demo:

This is fine at moment, but the problem is now coming up:

So that is my problem, in this example why doesn't button "B" turn off as it is now not the answer?

Upvotes: 0

Views: 86

Answers (1)

jeffjenx
jeffjenx

Reputation: 17487

Instead of removing the class for the answers variable, I think you need to remove the class from all items containing the class answerBtnsOn.

$( '.answerBtnsOn' ).removeClass( 'answerBtnsOn' ).addClass( 'answerBtnsOff' );

Do this first, as it removes all instances of that class, then add the class to answers that require it.

You may also wish to refer to the jQuery manual for .toggleClass() for ideas on how to improve on what you already have.

Upvotes: 1

Related Questions