I'm new to alpineJS, so this might be a silly question. I try to increase an input field by 1, and submit the new value (preferably with a small delay).
I currently have:
<input type='button'
value='+'
class='qtyplus plus'
field='quantity'
x-on:click="qty++ && $event.target.form && $event.target.form.dispatchEvent(new Event('submit'));" />
This increases the value of the input form by 1, and submits the form. The problem is that the submitted value is the old value, and not the new one.
Any help with this is much appreciated!
The &&
operator in JavaScript is used to test conditions for true/false. You should instead use ;
to put multiple commands in a single click. JavaScript does some unexpected conversions of values to true/false values. I'm surprised it works even partially. The mysteries of JavaScript! 😆
MDN has some good info on the && operator - called Logical AND
Here's your code sample with the change. I also made a couple of other changes using Alpine JS features:
$event.target.form
(not useful for you I think, but might be useful for others reading this question)submit()
method you can use. MDN has good info on this as well.<form x-ref="myform">
<input
type='button'
value='+'
class='qtyplus plus'
field='quantity'
@click.debounce="qty++; $refs.myform.submit()" />
</form>
After some more debugging I found the solution by using two on-click events, one that works directly and one that is delayed. This solved the issue for me.
<input type='button'
value='-'
class='qtyminus minus'
field='quantity'
x-on:click="qty--;"
@click.debounce.2000ms="$event.target.form.submit();"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With