I'm having an issue where I'm trying to pass number values from HTML (liquid) to Stimulus, but Stimulus is reading them as strings why is this happening?
The values are being pulled from an API, the relevant JSON looks like this:
{
"min": 1,
"max": 5,
"value": 3,
}
I'm passing value
, max
, and min
to my input component's controller like so:
<input type="text"
id="{{ id }}"
name="{{ id }}"
min="{{ min }}"
max="{{ max }}"
value="{{ value }}"
pattern="\d*"
data-selector-target="selector"
data-selector-value="{{ value }}"
data-selector-min="{{ min }}"
data-selector-max="{{ max }}"
class="selector p-1 w-9 text-center">
And I'm reading the values within my controller. If I console log the values, like in test()
below:
import { Controller } from "@hotwired/stimulus";
export default class extends Controller {
static targets = ['selector'];
static values = {
value: Number,
min: Number,
max: Number
}
test() {
console.log({
value: this.selectorTarget.value,
typeofvalue: typeof(this.selectorTarget.value),
min: this.selectorTarget.min,
typeofmin: typeof(this.selectorTarget.min),
max: this.selectorTarget.max,
typeofmax: typeof(this.selectorTarget.max)})
}
}
I get the following results in my console:
value: "3"
typeofValue: "string"
min: "1"
typeofMin: "string"
max: "5"
typeofMax: "string"
Does anyone know why that's happening?
Thanks!
It is because you typed your
<input>
to text.If you want it to consider the values as Numbers, then you have to type it so.