dumb11
dumb11

Reputation: 129

how to make the row change color whenever a button clicked and go back to original color when clicking again

When the button is clicked, I want to change the colour, and when the same button clicked, I want to go back to the original colour. Right now when button is clicked, all the rows change the color.

html

<table>
      <tbody ng-repeat="field in availableFields">
        <tr  ng-class="{'orderTypeTableRowSelected':tableRowTrueOrFalse}">
                <td style="padding:3px;">{{field.name}}</td>
                <td style="padding:3px;">
                <button type="button" ng-click="orderTypeTableRowSelected(field)" class="btn btn-danger" style="margin-left:10px;"><i class="fas fa-check"></i>&nbsp;Required</button>
        <button type="button" class="btn btn-warning"><i class="fas fa-check"></i>&nbsp;Default&nbsp;&nbsp;&nbsp;</button>
                </td>

    </tr>
    </tbody>
</table>

CSS

<style>

    .orderTypeTableRowSelected {
        background-color: #E0F7FA;
    }
</style>

angular

        $scope.tableRowTrueOrFalse = false;
        $scope.orderTypeTableRowSelected = function (field) {
            $scope.tableRowTrueOrFalse = !$scope.tableRowTrueOrFalse;
            console.log(field);
        };

Upvotes: 0

Views: 111

Answers (1)

Sujil Maharjan
Sujil Maharjan

Reputation: 1377

The problem here is that you have a list of values but only one boolean representing all of them.

tableRowTrueOrFalse should be an array of boolean values instead of a boolean value. Then you should fill the array with false as default.

$scope.tableRowTrueOrFalse = Array(availableFields.length).fill(false);

In your html, it would be something like:

<table>
      <tbody ng-repeat="field in availableFields">
        <tr  ng-class="{'orderTypeTableRowSelected':tableRowTrueOrFalse[$index]}">
                <td style="padding:3px;">{{field.name}}</td>
                <td style="padding:3px;">
                <button type="button" ng-click="orderTypeTableRowSelected(field, $index)" class="btn btn-danger" style="margin-left:10px;"><i class="fas fa-check"></i>&nbsp;Required</button>
        <button type="button" class="btn btn-warning"><i class="fas fa-check"></i>&nbsp;Default&nbsp;&nbsp;&nbsp;</button>
                </td>

    </tr>
    </tbody>
</table>

Then in your function,

$scope.orderTypeTableRowSelected = function (field, index) {
            $scope.tableRowTrueOrFalse[index] = !$scope.tableRowTrueOrFalse[index];
            console.log(field);
        };

Upvotes: 1

Related Questions