6

I am new to alpine.js and i need to toggle the innerText of an element, does anyone know ho can i combine showing an element and changing the innerText of another element? here is my code

<div x-data="{ numOrder: false, delNumOrder: 'Remove your order number' }">
  <button x-on:click="numOrder = !numOrder">
  Insert your order number</button>
  <input x-show="numOrder" type="text" placeholder="Order Number">
</div>

I need to overide the button text by delNumOrder, i have tried using x-text :

<button x-on:click="numOrder = !numOrder" x-text="delNumOrder = !delNumOrder">

Can i use something like ?

<div x-data="{ numOrder: false, delNumOrder = delNumOrder ? 'Insert your order number' : 'Remove your order number' }"></div>

1 Answer 1

11

You can use an expression inside of x-text, in this case the ternary for the text: numOrder ? 'Remove your order number': 'Insert your order number'. You probably want to do something like the following:

<div x-data="{ numOrder: false }">
  <button
    x-on:click="numOrder = !numOrder"
    x-text="numOrder ? 'Remove your order number': 'Insert your order number'"
  ></button>
  <input x-show="numOrder" type="text" placeholder="Order Number">
</div>
Sign up to request clarification or add additional context in comments.

2 Comments

Yep, exactly ;-)
Just a note, ternary statements work best with boolean values or explicit truthy/falsy values. I was checking whether an empty object was falsy and it wasn't working because [] and {} are both truthy as outlined here developer.mozilla.org/en-US/docs/Glossary/Truthy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.