How to change the color of a div via javascript with one condition

Asked

Viewed 279 times

2

I’m trying to change the color of a div if the following condition is true, if( @ViewBag == "reservado" ), but I’m not succeeding, could someone tell me how the code would look with this condition described above?

I’m programming on Asp.NET

To div that I want to change the color is this:

<div class="num">001</div>

Last code I tried:

function trocaCor(){
    var condi = @ViewBag.status;

    if( condi == "reservado"){
        document.getElementById("num").style.backgroundColor = green;
    }

}

but I don’t know if it’s right, I want when the page is loaded that condition (if it’s correct) to be executed.

I also tried the following code:

if( @ViewBag == "reservado" ){
    $('.num').css('background-color','#000000');
}

But it didn’t work

1 answer

1

Victor, the problem of using the Javascript is that if it is an external file .js will not work because the @ViewBag only works on the page .cshtml (if you are VB, .vbhtml).

A simple way would be to create a class css with the style you want:

.reservado {
   background-color: #000000
}

In cshtml, make the condition, and add the class to a variable if true, otherwise leave empty, not to add any class:

string classeReservado = (@ViewBag.status == "reservado") ? "reservado" : "";

Dai, go from the div and use this variable to apply the class:

<div class="@classeReservado">

If you still want to use Javascript and the file is external, you need to create the variable inside the file .cshtml, which is processed by asp-net and can read the contents of ViewBag:

var condi = '@ViewBag.status';
  • Ricardo, Obrigado, got it with the following code: var someStringValue = '@(Viewbag.statusAcomo1)'; if (someStringValue == "reserved") { $('.num1'). css('background-color', '#ffa500'); }

Browser other questions tagged

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