Change color button when click with Razor Page

Viewed 2248

This is the button that needs to change color when click. This is from a Razor page. I have tried the javascript code but it gives an error when I put in & I tried css code too(focus & active), didn't work. I'm new to this code. Please help. I just want something like this

enter image description here

<div class="row">
  <div class="column" style="width:30%">
    <div class="btn-group">
      <button type="button" class="btn btn-primary" style="outline-color:red" @onclick="() => UpdateTheChart(11)">@Language.T35</button>
      <button type="button" class="btn btn-primary" @onclick="() => UpdateTheChart(12)">@Language.T36</button>
      <button type="button" class="btn btn-primary" @onclick="() => UpdateTheChart(13)">@Language.T37</button>
    </div>
  </div>
  <div class="column" style="width:70%">
    <div class="btn-group">
      <button type="button" class="btn btn-primary" @onclick="() => UpdateTheChart(21)">@Language.T138</button>
      <button type="button" class="btn btn-primary" @onclick="() => UpdateTheChart(22)">@Language.T38</button>
      <button type="button" class="btn btn-primary" @onclick="() => UpdateTheChart(23)">@Language.T39</button>
      <button type="button" class="btn btn-primary" @onclick="() => UpdateTheChart(24)">@Language.T40</button>
    </div>
  </div>
</div>
</div>
This is the full code here. Im new with this code. Please tell me how to put a js code without error ( error no component )

 @page "/results"
@inject Blazored.LocalStorage.ISyncLocalStorageService localStore
@inject IJSRuntime JSRuntime;
@inject Toolbelt.Blazor.I18nText.I18nText I18nText

<h1>@Language.T8</h1>

<div>
    <div class="row">
        <div class="column" id="chartColumn" style="width:80%;text-align:center">
            <canvas id="myChart"></canvas>
        </div>
        <div class="column" style="width:20%;text-align:center;font-size:1.5vw">
            <br />
            <br />
            <br />
            <br />
            <span>
                @ResultInText <br />
            </span>
            <h1 style="font-weight:bolder">@FilterSavings</h1>
            <br />
            <br />
            <span>
                @WasteTextPaper<br />
                @WasteTextPlastic
            </span>
            @if (SelectedChartCategory == 13)
            {
                <br />
                <br />
                <br />
                <br />
                <br />
            }
            <span style="font-size:0.4vw">@DisclaimerText</span>
        </div>
    </div>
    <hr />

    <div class="row">
        <div class="column" style="width:30%">
            <b>@Language.T33</b>
        </div>
        <div class="column" style="width:70%">
            <b>@Language.T34</b>
        </div>
    </div>

    <div class="row">
        <div class="column" style="width:30%">
            <div class="btn-group">
                <button type="button" class="btn btn-primary" style="outline-color:red" @onclick="() => UpdateTheChart(11)">@Language.T35</button>
                <button type="button" class="btn btn-primary" @onclick="() => UpdateTheChart(12)">@Language.T36</button>
                <button type="button" class="btn btn-primary" @onclick="() => UpdateTheChart(13)">@Language.T37</button>
            </div>
        </div>
        <div class="column" style="width:70%">
            <div class="btn-group">
                <button type="button" class="btn btn-primary" @onclick="() => UpdateTheChart(21)">@Language.T138</button>
                <button type="button" class="btn btn-primary" @onclick="() => UpdateTheChart(22)">@Language.T38</button>
                <button type="button" class="btn btn-primary" @onclick="() => UpdateTheChart(23)">@Language.T39</button>
                <button type="button" class="btn btn-primary" @onclick="() => UpdateTheChart(24)">@Language.T40</button>
            </div>
        </div>
    </div>
</div>


@code {//handles initialization
    I18nText.Language Language = new I18nText.Language();
    List<float> retResultMHC = null;
    List<float> retResultCom = null;
    string retResultMHCProduct = "";
    string retResultCOMProduct = "";
    double retResultCostSavings = 0;
    double retResultTimeSavings = 0;
    double retResultWasteReduction = 0;
    double retResultWastePaper = 0;
    double retResultWastePlastic = 0;
    string retResultWasteFlag = "";
    string retResultCostFlag = "";
    string retResultTimeFlag = "";
    string FilterSavings = "";
    string WasteTextPaper = "";
    string WasteTextPlastic = "";
    string retCurrency = "";
    string DisclaimerText = "";
    string ResultInText = "Cost savings for all patients during a year";
    int SelectedChartCategory = 11;
    int SelectedChartPeriod = 24;
    int CalChartPeriod = 1;
    string SelectedResultFlag = "savings";
    string PeriodUOM = "year";

    protected override void OnInitialized()
    {
        InitializeLocalStorage();
        if (retResultMHC != null && retResultCom != null)
        {
            UpdateTheChart(11);
        }
    }

    protected override async Task OnInitializedAsync()
    {
        Language = await I18nText.GetTextTableAsync<I18nText.Language>(this);
        ResultInText = Language.T118 + Language.T127;
    }

    private void InitializeLocalStorage()
    {
        retResultMHCProduct = localStore.GetItemAsString("Result-MHC-Product");
        retResultCOMProduct = localStore.GetItemAsString("Result-COM-Product");
        retResultMHC = localStore.GetItem<List<float>>("Result-MHC");
        retResultCom = localStore.GetItem<List<float>>("Result-COM");
        retResultCostSavings = localStore.GetItem<double>("Result-Cost-Savings");
        retResultTimeSavings = localStore.GetItem<double>("Result-Time-Savings");
        retResultWasteReduction = localStore.GetItem<double>("Result-Waste-Reduction");
        retResultCostFlag = localStore.GetItemAsString("Result-Cost-Flag");
        retResultTimeFlag = localStore.GetItemAsString("Result-Time-Flag");
        retResultWasteFlag = localStore.GetItemAsString("Result-Waste-Flag");
        retResultWastePaper = localStore.GetItem<double>("Result-Waste-Paper");
        retResultWastePlastic = localStore.GetItem<double>("Result-Waste-Plastic");
        retCurrency = localStore.GetItemAsString("CurrencyKey");
    }
}

@code{//handles chart
    private IJSObjectReference _jsModule;

    //this will be the live code
    private async Task UpdateTheChart(int clickedButton)
    {
        //assign the selected parameters
        if (clickedButton == 11 || clickedButton == 12 || clickedButton == 13)
            SelectedChartCategory = clickedButton;
        else
            SelectedChartPeriod = clickedButton;

        if (SelectedChartPeriod == 21)
        {
            PeriodUOM = Language.T124;
            CalChartPeriod = 365;
        }
        else if (SelectedChartPeriod == 22)
        {
            PeriodUOM = Language.T125;
            CalChartPeriod = 52;
        }
        else if (SelectedChartPeriod == 23)
        {
            PeriodUOM = Language.T126;
            CalChartPeriod = 12;
        }
        else if (SelectedChartPeriod == 24)
        {
            PeriodUOM = Language.T127;
            CalChartPeriod = 1;
        }
        else
        {
            PeriodUOM = Language.T127;
            CalChartPeriod = 1;
        }

        ResultInText = "";
        //things to do before showing the selected chart
        if (SelectedChartCategory == 11)
        {
            if (retResultCostFlag == "savings")
                ResultInText = Language.T118 + PeriodUOM;
            else
                ResultInText = Language.T119 + PeriodUOM;
                        
            WasteTextPaper = "";
            WasteTextPlastic = "";

            FilterSavings = string.Format(retCurrency + "{0:n0}", retResultCostSavings / CalChartPeriod);
            DisclaimerText = "";
        }
        else if (SelectedChartCategory == 12)
        {
            if (retResultCostFlag == "savings")
                ResultInText = Language.T120 + PeriodUOM;
            else
                ResultInText = Language.T121 + PeriodUOM;

            WasteTextPaper = "";
            WasteTextPlastic = "";

            FilterSavings = string.Format("{0:n0}", retResultTimeSavings / CalChartPeriod) + " " + Language.T134;
            DisclaimerText = "";
        }
        else if (SelectedChartCategory == 13)
        {
            if (retResultCostFlag == "reduction")
                ResultInText = Language.T122 + PeriodUOM;
            else
                ResultInText = Language.T123 + PeriodUOM;

            WasteTextPaper = Language.T128 + string.Format("{0:n2}", retResultWastePaper / CalChartPeriod) + " " + Language.T135;
            WasteTextPlastic = Language.T129 + string.Format("{0:n2}", retResultWastePlastic / CalChartPeriod) + " " + Language.T135;

            FilterSavings = string.Format("{0:n2}", retResultWasteReduction / CalChartPeriod) + " " + Language.T135;
            DisclaimerText = Language.T136;
        }

        //calling js to make the chart
        _jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./scripts/MakeChart.js");
        if (SelectedChartCategory == 11)
        {
            await _jsModule.InvokeVoidAsync("showChartCost", CalChartPeriod, Language.T131, Language.T132, Language.T133);
        }
        else if (SelectedChartCategory == 12)
        {
            await _jsModule.InvokeVoidAsync("showChartTime", CalChartPeriod, Language.T130);
        }
        else
        {
            await _jsModule.InvokeVoidAsync("ShowChartPic");
        }
    }
}
4 Answers

Are you sure you want to use Javascript? You can use variables to update properties in Blazor:

<button style="background-color:@bgcolor" @onclick=SetColor>Click</button>

@code
{
   string bgcolor {get; set;} = "00f"; // (starting value)

   void SetColor(){
       bgcolor = "#fd7"; (will update instantly)
       StateHasChanged();  // may not be required, but I'm at work right now, so can't check
   }
}

Better would be to use a variable to set the CLASS of the object:

<button class="@buttonclass" @onclick=SetColor>Click</button>
    
    @code
    {
       string buttonclass{get; set;} = "btn btn.primary"; // (starting value)
    
       void SetColor(){
           buttonclass= "btn btn.secondary";
           StateHasChanged();  // may not be required, but I'm at work right now, so can't check
       }
    }

Also, it looks like you have a lot of repeated entries. In Blazor, consider having a List with all your various languages, and do this in your markup:

<div>
    @foreach (item in LanguageItems){
        <button class="btn btn-primary" >@item.Language</button>
    }
</div>
@code
{
     List<MyLanguageClass> LanguageItems {get; set;}
     protected override async Task OnInitializedAsync(){
          // Loadup your list of items from a database or whatever
     }
}

Ok. So what you can do in javascript is to write `document.getElementById("id of button").backgroundColor="whatever color you need to set in button"'

<button onclick="updateColor(this)">click me</button>

inside of javascript

function updateColor(btn){
    btn.style.backgroundColor = 'red';
    btn.style.color = 'white';
}

I'll explain what's going on here.

Inside the button the onclick attribute takes a function (or a javascript instruction) and you can pass the clicked button inside the arguments as this.

then you can modify the clicked element in javascript function.

edit:

to use JavaScript you use the script tag as follows...

<script>
    // your JavaScript code
</script>

just put the above script tag at the end of the body.

It's not good to write all JavaScript code inside the html script tag.

So instead you can just add src to the script tag and link to a separate javascript file like...

<script src="./yourpath/filename.js"></script>

I use css(.btn:focus) and it can work.Here is a demo:

<div>
    <div class="row">
        <div class="column" style="width:30%">
            <div class="btn-group">
                <button type="button" class="btn btn-primary">Language.T35</button>
                <button type="button" class="btn btn-primary">Language.T36</button>
                <button type="button" class="btn btn-primary">Language.T37</button>
            </div>
        </div>
        <div class="column" style="width:70%">
            <div class="btn-group">
                <button type="button" class="btn btn-primary">Language.T138</button>
                <button type="button" class="btn btn-primary">Language.T38</button>
                <button type="button" class="btn btn-primary">Language.T39</button>
                <button type="button" class="btn btn-primary">Language.T40</button>
            </div>
        </div>
    </div>
</div>
<style>
    .btn:focus {
        background-color: #ff6e40;
    }
</style>

result: enter image description here

Related