• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

18
Views
Could I have two onclick events in this one element?

So I do know that it is possible to have two onclick events in one element. But I'm not sure how to do it exactly for my situation. Is there another way of doing this that I'm not trying? I'm trying to add the ShowAlert() method.

My code looks like this:

<button class="btn btn-primary" @onclick="e => AddToCart(context)">Add To Cart</button>

And I have tried(I get an error every time I try these):

<button class="btn btn-primary" @onclick="e => AddToCart(context); ShowAlert();">Add To Cart</button>

and:

<button class="btn btn-primary" @onclick="ShowAlert(); e => AddToCart(context)">Add To Cart</button>

Here is my ShowAlert method in case it is needed:

@code
{
    async Task ShowAlert()
    {
        await JsRuntime.InvokeVoidAsync("createAlert");
    }
}

Any help/advice is appreciated! Thank you!

about 1 month ago ·

Juan Pablo Isaza

3 answers
Answer question

0

It looks like you're using some library I am unfamiliar with, so not sure if any of this is feasible.

  1. Do you need to attach these events inline on the element? The first thing my mind goes to is attaching them in JS

  2. If #1 is not possible, how about making a single joined function that calls both of them?

function addToCartAndShowAlert(context) {
   AddToCart(context)
   ShowAlert()
}
<button class="btn btn-primary" @onclick="e => addToCartAndShowAlert(context)">Add To Cart</button>

Just ideas to try, best of luck to you

about 1 month ago · Juan Pablo Isaza Report

0

The following should normally work, wrapping it in parentheses to call it like an anonymous function :

<button @onclick="(e => AddToCart(context))();ShowAlert();">Hi</button>

function AddToCart() {
  alert('add to cart');
}

function ShowAlert() {
  alert('show alert');
}
<button onclick="(e => AddToCart())();ShowAlert();">Hi</button>

about 1 month ago · Juan Pablo Isaza Report

0

You can try this:

 <button class="btn btn-primary" @onclick="@(() => { AddToCart("content"); ShowAlert(); })">Add To Cart</button>
@code
{
    async Task ShowAlert()
    {
        await JsRuntime.InvokeVoidAsync("createAlert");
    }
    void AddToCart(string val)
    {
        StateHasChanged();
    }
}

result: enter image description here

about 1 month ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.