Change input color according to value

2

Good afternoon Friends

I have an input with the name of MARGIN, where a value is displayed according to some calculations that are made ... I need the input to change the color to red if this value is less than 25, if it is bigger it maintains her color (white) ...

NOTE: I have the input value, where this input the sellers manipulate the value of a product trying to always keep the margin above 25%, but if it download I want the color to change, all without refresh. >

<label for="valor_unitario">Vlr. Unit.</label>
<input type="text" name="valor_unitario" id="valor_unitario" style="text-align: center" required>

<label for="quantidade">Qtd.</label>
<input type="text" name="quantidade" id="quantidade" style="text-align: center" required>

<label for="valor_total">Vlr. Total</label>
<input type="text" name="valor_total" id="valor_total" readonly>

<label for="margem">Margem</label>
<input type="text" name="margem" id="margem" style="text-align: center" readonly>

So that they do not get lost, the total value input shows the value of (unit value * quantity) .. what interests us is unit value and margin

    
asked by anonymous 09.05.2018 / 20:21

2 answers

3

Since you are using Jquery, you can use change , it will check every time there is a change in input and you can apply some logic to that change.

In this CodePen , I did it only in the first input, in case I need to apply in others, just follow the same logic!     

09.05.2018 / 20:51
0

Use jQuery :) You can use "on change" with a class for code optimization. Then just add the "class" where you want to apply the colors. Here is an example:

$(document).ready(function(){

  $('.valor').on('change',function(){
    var valor = $(this).val();

    if(valor < 25){
      $(this).addClass("negativo").removeClass("positivo");
    }else{
      $(this).addClass("positivo").removeClass("negativo");
    }
  });
  
});
.negativo {
  background: red;
  color: #fff;
}

.positivo {
  background: green;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><labelfor="valor_unitario">Vlr. Unit.</label>
<input type="text" name="valor_unitario" id="valor_unitario" class="valor" required>

The code does is add a "positive" or "negative" class according to the value. You can create as many possibilities as you want. Positive, negative, neutral, etc.

    
09.05.2018 / 20:55