keisaac
keisaac

Reputation: 356

Django template onclick inline html javascript alternative

I read that using onclick is deprecated and bad practice.

I have this do_something function that will proccess the data inside of onclick. How I can convert this to javascript:

{% for user in all_user %}
<tr>
    <td>{{ user.code }}</td>
    <td>
        <button type="button" onclick="do_something('{{ user.name }}', '{{ user.age }}', 1, '{{ user.desc }}');">small</h6></button>
    </td>
</tr>
{% endfor %}

Upvotes: 1

Views: 2988

Answers (1)

AdonisN
AdonisN

Reputation: 489

  1. Set a class selector on the buttons so you can apply the event listener to it via Javascript.
  2. Your function requires parameters that are unique per user, so you'll need to set those parameters as data attributes on each button.

{% for user in all_user %}
  <tr>
      <td>
          <button class="user-action-btn" type="button"  
          data-name="{{ user.name }}" 
          data-age="{{ user.age }}" 
          data-desc="{{ user.desc }}">small</button>
      </td>
  </tr>
{% endfor %}

  1. In Javascript, get the elements by class name and set the event handler for each.

Here's an example of the code in Javascript

(function() {
        var classname = document.getElementsByClassName("user-action-btn");

        var myFunction = function(e) {
            e.preventDefault();
            var name = this.getAttribute("data-name");
            var age = this.getAttribute("data-age");
            var desc = this.getAttribute("data-desc");
            do_something(name, age, 1, desc)
        };

        for (var i = 0; i < classname.length; i++) {
            classname[i].addEventListener('click', myFunction, false);
        }
})();

And here's the JQuery equivalent

$( document ).ready(function() {
    $('.user-action-btn').on('click', function(e){
        e.preventDefault();
        var name = $(this).data('name');
        var age = $(this).data('age');
        var desc = $(this).data('desc');
        do_something(name, age, 1, desc);
});

Upvotes: 4

Related Questions