Home > OS >  Could I have two onclick events in this one element?
Could I have two onclick events in this one element?

Time:11-08

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!

CodePudding user response:

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

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related