Joe Robert Joe Robert - 29 days ago 5
CSS Question

Change the values of the 2nd column when a user clicks on the heading of the 2nd column of a table

I have a table on my page and I was wondering if it was possible to change the values of the 2nd column when a user clicks on the heading of the 2nd column.

For example,

-----------------------------
| 1st heading | 2nd heading |
|-------------|-------------|
| | |
| | |
| | |
| | |
| | |


Now when the user clicks on "2nd heading" the value of the second column will change and the name of the heading will change too ( from 2nd heading to 3rd heading )

Answer

This is a simple task using jquery. First add id to the columns. The second heading column should be like this

Without jQuery

<th id="th2" onclick="changeVal()">2nd Heading</th>

    <script>
    function changeVal() {
    document.getElementById("th2").innerHTML = "3rd Heading";
    }
    </script>

With jQuery This section has been updated. I added a data-state attribute the column head, so when you toggle values it will record the last change.

 <th id="th2" data-state="2">2nd Heading</th>

Add jquery code like this after linking a jquery file

<script type="javascript" src="path_to_jquery.js" />
 <script>
    $("#th2").click(function() {
    var state = $(this).attr("data-state");

    if(state=="2") {
    $(this).html("3rd Heading");
    $(this).attr("data-state", "3");
    } else if(state=="3") {
    $(this).html("2nd Heading");
    $(this).attr("data-state", "2");
    }
    });

//you can replace $(this) with $("#th2") or thr id of another element or table cell to manipulate the value inside
</script>

Try it out and give feedback