JustJohn
JustJohn

Reputation: 1460

Trying to change <td> background color based on checkbox value on Razor page

I would like this to turn red whenever the checkbox inside it is checked. The Html.DisplayFor makes things a little more complicated. The Inactive field in SQL server table is boolean, zero or one.

<td align="center">

        @Html.DisplayFor(modelItem => item.Inactive)

</td>

When looking at the table, the value is either 0 or 1. The page shows a checkbox which is desired but I am stuck trying to reference it's value and set the background-color of the surrounding table cell.

Upvotes: 0

Views: 171

Answers (1)

Yiyi You
Yiyi You

Reputation: 18159

Try to use EditFor to replace DisplayFor,and then add the following js to your view:

function changeColor(t) {
            if (t.checked) {
                $(t).parent().css('background', 'red');
            } else {
                $(t).parent().css('background', 'none');
            }
            
        }
        $('input[type=checkbox]').change(function () {
            changeColor(this);
        })
$(function () {
            $('input[type=checkbox]').each(function () {
                changeColor(this);
            });
           
        })

Upvotes: 1

Related Questions