How to change the color of buttons when selecting a radio input?

Asked

Viewed 1,322 times

4

I have this form Formulário que muda os botões ao selecionar o input radio

When you check the "Bills to Pay" radio input, I need the buttons to turn red.

I’m using Angularjs, so I used ng-if, but the code was quite extensive.

How could I do it in a simpler way?

  • 3

    puts the code here jsfiddle.net for us to see!

  • 2

    Shows your code to help with the analysis. You can also use the ng-class that is conditional

  • Angular offers many validation rules that we can use, ng-minlength, ng-maxlength and several others. Check on this link how to make the change according to filling in fields in the form, the same can be applied in your situation. http://airtonvancin.com/blog/angularjs-validacao-de-formulario/

1 answer

6


You don’t need to use ng-if in this case. You can create a parent class for your buttons inside. When the checkbox is activated, you use ng-class to add a class to the parent container in case the desired checkbox is selected.

So it would affect the buttons.

angular.module('app', [])
.container-btn .btn{
  background: green;
  border:none;
  border-radius:4px;
  padding:10px;
  color:white;
}

.container-btn.marked .btn{
   background: red;
   
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-init="a_pagar=false">
    <div>
        <label>
            <input type="radio" ng-value="true" ng-model="a_pagar">
            Contas a pagar
        </label>
        <label>
            <input type="radio" ng-value="false" ng-model="a_pagar">
            Contas a pagar
        </label>
    </div>

    <div class="container-btn" ng-class="{'marked' : a_pagar}">
        <button class="btn">Vencidos</button>
        <button class="btn">Hoje</button>
    </div>
</div>

Note that the class container-btn affects the button that has the class btn. If the checkbox is checked, the marked classé adicionada acontainer-btn`.

To understand better, the ng-class serves for you to add classes dynamically by Angular. You need to define a Objeto with indexes containing an expression. If the expression is evaluated as true, the index value will be added to the element class.

You can read more about the ng-class in documentation;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.