Search code examples
javascriptstimulusjs

Error when trying to create a finder on a table


I am trying to replace jquery of my application made in django, and I am trying with stimulus js, because it seems like a good option together with turbolink, but I am having a problem when creating a datatable, when entering text in the search engine it does correctly and it returns what I write, but the problem is in the table because the browser console returns an undefined value. This is my html:

<div data-controller="search">
                        <input type="text" placeholder="Buscar..." maxlength="15" data-action="search#searchTable"data-search-target="q">
                        <table class="highlight centered">
                            <thead>
                                <tr>
                                    <th>Tipe de Tarea</th>
                                    <th>Estado</th>
                                    <th>Fecha de Creacion</th>
                                    <th>Accion</th>
                                </tr>
                            </thead>

                            <tbody>
                                <tr>
                                    {% for field in object_list %}
                                    <td data-search-target="name">{{ field.name }}</td>
                                    <td>{{ field.status|yesno:"Visible, No visible" }}</td>
                                    <td>{{ field.created_at }}</td>
                                    <td>
                                        <a href="#!">editar</a>
                                    </td>
                                    {% endfor %}
                                </tr>
                            </tbody>
                        </table>
                    </div>

This is my controller:

const application = Stimulus.Application.start();
const { Controller } = Stimulus;

application.register(
  'search',
  class extends Controller {
    static get targets() {
      return ['q', 'name'];
    }

    searchTable() {
      console.log(this.nameTarget.value);
    }
  }
);

Solution

  • I think you're mixing up your targets. q is the input and would have a value. name is a table cell and so would only have an innerHTML. Instead it should be:

    searchTable() {
      console.log(this.qTarget.value);
    }
    

    But I would suggest you go further and pass in the event to your searchTable function. Then you don't need a data-target on the input.

    searchTable(e) {
      console.log(e.srcElement.value);
    }