Matthew Czajka
Matthew Czajka

Reputation: 189

How to change css style based on value

I have a boolean array that I am displaying in a razor foreach loop. Within the loop I am displaying the different values within the array. Is it possible,if so how, to change the css based on the value it is displaying?

For example

if (@status == true) THEN color = green; if (@status == false) THEN color = red.

Upvotes: 12

Views: 33637

Answers (4)

Overlord
Overlord

Reputation: 2906

I came across this question having the same problem, however I have implemented another solution, using c#/razor/css and no javascript. Someone might like this better.

First: define the possible values as an enumeration:

 public class enum MyRateTyp{
    Level1,
    Level2,
    Level3
  }

Second: Find a place where, given the number on which the style will be based, the conversion will take place. In my case I added an extension method to the int type.

public MyRate Evaluate(this int i)
{
  MyRate answer = MyRate.Level1;
  if(i<50)
    {
      answer = MyRate.Level1;
    }
    .
    //All if statements here
    .
  if (i>100)
  {
    answer = MyRate.Level3;
  }
  return answer;
}

Third: On your .css file, define the style for each possible value, like so:

.Level1{
     /*Style here for level 1*/
    }
.Level2{
   
      /* Style here for level 2*/
   }
    /*
      Other Styles here
    */

Finally On the Razor page, assign the extension method to the css class of the element you want to change the style based on the value. For example.

The level is <p class="@(myInt_variable.Evaluate())"> @(myInt_Variable) </p>

Upvotes: 0

Nick De Jaeger
Nick De Jaeger

Reputation: 1249

$('.test').each(function() {
  if(parseInt($(this).css('font-size')) > 16) {
    $(this).css('color', 'green');
  }
});
.test {
  font-size: 18px;
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="test">Javascript manipulation: Green when largen than 16px</p>

Upvotes: 2

Marco Hengstenberg
Marco Hengstenberg

Reputation: 864

If I understand your question correctly, you could add a data-attribute to the HTML element and alter the value (for example with Javascript) to/from "true/false" and use that in your CSS like so:

<element data-status="true">Content</element>
<element data-status="false">Content</element>

[data-status="true"] {
    color: green;
}
[data-status="false"] {
    color: red;
}

Upvotes: 20

Picot
Picot

Reputation: 1

It is possible to change the color by putting an event on the box. This is done in javascript "AddEventListener"

Upvotes: -2

Related Questions