Using AlpineJS I have the following:
<div x-data="pricing()" x-init="data = { plan: 'a' }">
<p><span x-text="calculate() + '€'"></span>per session</p>
<select x-model="data.plan">
<option value="a">A</option>
<option value="b">B</option>
</select>
</div>
export default function pricing() {
return {
data: {
plan: "",
},
calculate() {
if (this.data.plan == "a")
return 20;
return 30;
}
}
}
How to hide the span
if calculate()
returns null
?
2
Answers
Your x-model controlled element needs to be inside your x-data container:
EDIT: to avoid calling calculate() twice each time, you can store the result inside the data object and recalculate it each time the model changes with the x-on:change attribute:
This might be more efficient, but the ‘Alpine way’ would probably just be to call the function twice.
An option can be adding a "watch" on the value:
In this example I’ve moved the init() function in the data object, passing the initial parameter
If you want to completely hide the price row, you must move x-show in the <p> tag: