Alpine: Conditional preventDefault()

Created on 5 Apr 2020  路  7Comments  路  Source: alpinejs/alpine

Docs say that I need to do this to use preventDefault():

<input type="checkbox" x-on:click.prevent>

How can i do that conditionally?

Most helpful comment

I actually managed to do this like this:

```

onClick(e){
if(something){
e.preventDefault();
}
}

All 7 comments

I don't think there is a way to do this conditionally.

One way might be duplicating the checkbox and wrapping each on an x-if so you can check the conditions there, and hide the checkbox based on the condition.

There's a way actually (it's just missing from the documentation).
If your handler return false, it will prevent the default behavior
x-on:click="return something !== null" like normal javascript

There's a way actually (it's just missing from the documentation).

If your handler return false, it will prevent the default behavior

x-on:click="return something !== null" like normal javascript

Ah yes. The same as a regular event listener, duh.

I actually managed to do this like this:

```

onClick(e){
if(something){
e.preventDefault();
}
}

@piotrpog Are you okay with closing this issue (and the other ones where you got a response)?
Only Caleb and the user who opened the issue can close it and if we leave them open they add noise in the list and it's not easy to see if there are real issues in the middle.
Thanks.

@SimoTod
sure, I will close it. But I feel we need some additional communications channel when people can just ask questions, so issues list don't get clogged.

Thanks. Yeah, an additional channel would be nice, expecially for questions that are not bugs or feature requests. On the other hand, there's a risk that it would become like a support centre with a lot of people asking for help because they haven't read the documentation first.
As you can understand, it's an open source project and all the guys who help with these questions have another job and limited time so a direct channel could be potentially disruptive.
I think github is okay for now, people just need to set their expectations correctly, answers can take a bit of time and possibly issues should be closed once resolved.

Thanks for understanding

Was this page helpful?
0 / 5 - 0 ratings