0

How can I change the table td background color when a radio button is clicked?

This is the view which generates 10 questions having 4 radio buttons each with the help of foreach loop. Making first radio button name ans[0],second ans[1] and so on

 <div class="col-lg-8" >
            <table class="table" style="width: 100%;">
            <?php 
            $i = 0;
            $ques = 1;            
            echo form_open('Menu/submit_ans', array('name' => 'quiz'));
            foreach ($quiz_array as $q){
            ?>    
            <td colspan="2"style="background-color: #337ab7;color:white;"><h4>Question No. <?php echo $ques?> </h4></td>
            <tr>
            <td style="background-color: #D3D3D3;color:white;" colspan="2"><h5><?php echo $q->ques;?></h5></td>
            <input hidden name="qid[]" type="text" value="<?php echo $q->qid;?>">
            <input hidden name="uid[]" type="text" value="<?php echo $user['id'];?>">
            </tr>
            <tr>
            <td><?php echo $q->ans_1;?></td>
            <td><input type="radio" class="myRadio" name="ans[<?php print $q->qid; ?>]" value="1"></td>
            </tr>
            <tr>
            <td><?php echo $q->ans_2;?></td>
            <td><input type="radio" class="myRadio" name="ans[<?php print $q->qid; ?>]" value="2"></td>
            </tr>
            <tr>
            <td><?php echo $q->ans_3;?></td>
            <td><input type="radio" class="myRadio"  name="ans[<?php print $q->qid; ?>]" value="3"></td>
            </tr>
            <tr>
            <td><?php echo $q->ans_4;?></td>
            <td><input type="radio" class="myRadio" name="ans[<?php print $q->qid; ?>]" value="4"></td>
            <input type="radio" hidden name="ans[<?php print $q->qid; ?>]" value="0" checked="checked">
            </tr>


            <?php 
                $i++;
                $ques++;
            }
            ?>
            </table>
            <center><button class="btn btn-success" type="submit">Submit!</button></a></center>
            <?php echo form_close();?>
        </div>

This is the table data which is in ANOTHER div.

 <table class="table">
            <tr>
            <thead>
                <th colspan="10">Answer Status</th>
            </thead>
            </tr>
            <tr>
            <td class="color">1</div></td>
            <td>2</td>
            <td>3</td>
            <td>4</td>
            <td>5</td>
            <td>6</td>
            <td>7</td>
            <td>8</td>
            <td>9</td>
            <td>10</td>
            </tr>
</table>

I want to change the background color of td for 1 when the user clicks the ans[0] radio button.

  • Possible duplicate of [Setting background-image using jQuery CSS property](http://stackoverflow.com/questions/512054/setting-background-image-using-jquery-css-property) – ppovoski Nov 09 '16 at 08:39
  • This is the same as http://stackoverflow.com/questions/512054, just replace background-image with background-color. – ppovoski Nov 09 '16 at 08:40
  • 1
    Definitely not the same question. The problem in this question is not changing a background color; it is creating the logic to match a status cell based on a clicked radio button. – Lars Gyrup Brink Nielsen Nov 09 '16 at 09:33
  • i will say it again, if you want to dynamically change the view, DOM elements, classes, ect on multiple type of event use a framework like AngularJS because it's one of it's main purposes and it will be a LOT more easier for you than trying to do that in simple js. – N.K Nov 09 '16 at 10:12
  • Suggestion noted. I am trying to learn AngularJS I just havent got the hang of it yet. But it is in my must-learn list! :) – Sahib Uz Zaman Nov 09 '16 at 10:15

5 Answers5

2

Matching your coding style: Modify your status table TD's so none have the colour class (and clean up that stray closing div - assuming thats a cut & paste issue)

    <table class="table">
    <tr>
        <thead>
            <th colspan="10">Answer Status</th>
        </thead>
    </tr>
    <tr>
        <td class="answer answer1">1</td>
        <td class="answer answer2">2</td>
        <td class="answer answer3">3</td>
        ...
    </tr>
</table>

Then add modify the output of your php so the radios look like

// For optional answers to Q1
<input type="radio" value="1,1" class="myRadio">
<input type="radio" value="1,2" class="myRadio">
...
// For optional answers to Q2
<input type="radio" value="2,1" class="myRadio">
<input type="radio" value="2,2" class="myRadio">
...

and change JS code to

$('.myRadio').on('change', function() {
    var aSelection = $(this).val().split(",") // split 1,2 into an array

    var tgt="answer" + aSelection[0] // first digit in radio btn val

    if ($(this).prop("checked")) {
        $("." + tgt).css({ backgroundColor: "green"});
    }
})

What did I do: I modified the radio button JQ selector to use a specific class instead of specifying all/any radio elements. This does not need to be a 'real' css class. It is just being used as a selector. The reason I suggest this is that otherwise your selector reacts to any radio button so that if your page contains any other radio's you will find this JS is fired when you were not expecting it. In all practical terms, using classes as selectors is only very slightly less speedy than element id's so there is no realistic performance issue with this approach.

I then assigned classes to the display TD's. When the radio is clicked we extract its value and use this to target the correct TD in the other table.

EDIT: I got the requirement wrong - it is actually a multi-choice quiz app. There are 2 tables. Table 1 acts as a progress indicator showing which questions from 1 - 10 have been answered. When a question is answered the cell representing that question in the progress table should become shaded. Table 2 has the questions and each question can have up to 4 answers, with a radio button being used as the UI element for selection of an answer. When the user makes a selection of an answer that event should cause the progress table shading to occur.

The difficulty here is that the value of the radio buttons has to serve both as a question number indicator AND a question option indicator. I opted to have these two indicators placed into the radio button value as 'q,a' where q is the question no and a the answer within the question, so '3,2' represents question 3 answer 2. The radio value is then split into an array and the question no used to target the appropriate TD in the progress table.

This introduces the issue that when the form is sent to the server the radio button values will be transmitted as 'q,a'. The OP will have to handle this on the server side. I am sure php can handle this.

Vanquished Wombat
  • 9,075
  • 5
  • 28
  • 67
  • This does change the background color, but the closest td property will not work in my case. My radio is in another table and the td i want to color is in another table. – Sahib Uz Zaman Nov 09 '16 at 08:49
  • My answer sheet looks like this 1 2 _ _ where 1 and 2 are questions. Right now when I press the first radio button it changes color of question 1 and when i press the second radio button (IN THE SAME QUESTION) it changes color of question 2 I have updated the code. Your answer does most part of the job though – Sahib Uz Zaman Nov 09 '16 at 09:12
  • @SahibUzZaman Updated to make the highlight on Q1 clear when the user clicks radio button 2, etc So the idea is to highlight the CURRENT question only. – Vanquished Wombat Nov 09 '16 at 09:18
  • No. right now what is happening, I have a 20 questions each with 4 answers(hence 4 radio buttons). And another table where I have an Answer Sheet where only question numbers are written from 1 to 20. When I answer the first question by selecting the first answer the 1 in Answer sheet is highlight. But when I select the second answer the 2 in Answer sheet is highlighted. Which shouldnt happen as that 2 is for the second question not for the answer. – Sahib Uz Zaman Nov 09 '16 at 09:29
  • @SahibUzZaman Ok so you have Q1 with radios for Answer 1 / 2 / 3 / 4, then Q2 with radios for Answer 1 / 2 / 3 / 4...etc ? And what you want is that when user clicks option 2 or Q1 then the Q1 in the answer sheet is lit - correct ? – Vanquished Wombat Nov 09 '16 at 09:36
  • @SahibUzZaman Last question - can I assume that you need the values of the radio buttons to be sent to a server? Meaning the value="1", "2", etc of the Q1 radios must be maintained? It might feel like a dumb question but bear with me. – Vanquished Wombat Nov 09 '16 at 09:44
  • I need the values of the radio button to store in the database. – Sahib Uz Zaman Nov 09 '16 at 10:15
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/127702/discussion-between-sahib-uz-zaman-and-vanquished-wombat). – Sahib Uz Zaman Nov 09 '16 at 10:36
1

you can grap the radio buttons and then handel their change event :

$('td input[type="radio"]').change(function(event)
{
if($(event.target).prop('checked'))
{
    /* send radio index from here */
    var index=    $(event.target).val();
    changeBackground(index);

}else
{
   /* some code if you want for false section */
}

})


function changeBackground(td_index)
{

   /* write you codes herer for changing the td color ...... use td_index paramerte */

}
0

Like this?

 $('input:radio').checked(function() {
      $(this).closest('td').addClass('highlight');
    });
    .highlight {
      background: green;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <tr id='game_1'>
      <td class='bowl'>Fiesta Bowl</td>
      <td id='radiocell'>
        <input type='radio' name=1 value='Arizona'></input>
      </td>
      <td class='team1'>Arizona</td>
      <td id='radiocell'>
        <input type='radio' name=1 value='Boise State'></input>
      </td>
      <td class='team2'>Boise State</td>
      <td class='gameDay'>January 1</td>
    </tr>

I hope that you can use this our tell me what you really want so I can write it for you :-) Copy of https://stackoverflow.com/a/27663896/7007968
I am not the writer of this code

Community
  • 1
  • 1
N. Smeding
  • 364
  • 2
  • 14
  • No. The radio button and td i want to color are in different tables and divs. This is basically a quiz application. I have a table with questions and radio button for answers. Another table to show the answer sheet. – Sahib Uz Zaman Nov 09 '16 at 08:31
  • ah okey give me a sec i will take a look – N. Smeding Nov 09 '16 at 08:32
0

Assuming that:

  1. The color class is the one that is used to highlight a status cell.
  2. You are unable to mark the status table with an ID for easier query selector matching. Because of this, the table class, and the "Answer Status" text is used for matching the status table.

Solution using jQuery

var
    statusCells
;

// Find all cells in the status table.
statusCells = $(".table:contains('Answer Status')").find("td");

// Match elements that have an ID that starts with "ans".
// Listen to "change" events on these radio buttons.
$("[id^='ans']").change(function onChange(event) {
    var
        radio,
        value
    ;

    // Find the clicked radio button.
    radio = $(event.target);
    // Take the value of the radio button.
    value = radio.val();

    statusCells
        // Remove previous highlighting.
        .removeClass("color")
        // Find the status cell with text matching the value of the clicked
        // radio button.
        .filter(":contains('" + value + "')")
        // Highlight the matching status cell.
        .addClass("color");
});
Lars Gyrup Brink Nielsen
  • 3,939
  • 2
  • 34
  • 35
0

You can add this code in your JS, it will definitely work i have tried it.

JS:

function changeColColor(){
var tds=$("td");
for(id in tds){
var text=tds[id].innerHTML;
if(text==1){
tds[id].style.backgroundColor="green";
}
}
}

If you want to add it as a class,

tds[id].className ="green";

where green will be defined like this,

.green{
background-color:green;
}

HTML:

And then call the function in the on-click of your radio button as shown below in an example,

<input type="radio" name="ans0" value="1" onclick="changeColColor()">
GraveyardQueen
  • 771
  • 1
  • 7
  • 17