Home > Back-end >  Stimulus not geting values from html
Stimulus not geting values from html

Time:09-27

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  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

CodePudding user response:

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").dataset.selectableIconurlValue)

Though your value may just be treated like a common JS dataset component. You lose every Turbo goodness such as a mutation observer 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. Maybe I am wrong too and there is a way to have it acknowledged by Stimulus...

  • Related