Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stimulus not geting values from html

I'm doing a basic controller and trying to get data from the HTML with the tag value.

The problem is that the data is always empty

<div data-controller="selectable">
  <div class="flex" data-selectable-iconurl="test" data-selectable-iconurl-value="test">
     something here
  </div>
</div>

Notice I did multiple combinations of the value tag ( from different posts) in order to verify if one is working.

Now when I try to access the values in the controller is always empty

// selectable_controller.js

import {Controller} from "@hotwired/stimulus"

export default class extends Controller {
  static values = {iconurl: String }

  connect() {
    console.log(this.iconurlValue)
  }

}

I double-checked the documentation and could not find why the value is not passed to the controller and is always empty

like image 404
Nonyck Avatar asked Jul 23 '26 23:07

Nonyck


1 Answers

When Stimulus controller is on the same element as the value, you should be able to retrieve the value:

<div data-controller="selectable" data-selectable-iconurl-value="test">

If your value needs to be set on a child element, then I suggest to just access it the old way :

console.log(this.element.querySelector("div.flex").dataset.selectableIconurlValue)

Though your value may just be treated like a classic HTML element dataset attribute. You lose every Turbo goodness such as observing any change to the value : https://dev.to/borama/stimulus-2-0-value-change-callbacks-what-are-they-good-for-4kho

Not sure why the required location of the value is not precised in the Stimulus Handbook. But the logic is having states on the Stimulus controller, just like what happens in different JS framework, so there is no reason to have the value elsewhere than on the controller anyway.

like image 173
Maxence Avatar answered Jul 26 '26 15:07

Maxence



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!