Home > Software design >  Toggle text on click on a query loop
Toggle text on click on a query loop

Time:10-18

I'm trying to make a section that lists content on a query and ends with a link that changes it's name upon click. In this context, 'objetos' displays data from a class that I then turn to html.

{% for i in objetos %}
...
<a onclick="change()" id="{{i.id}}">Fav</a>
    <script>
        function change() {
            var elem = document.getElementById("{{i.id}}");
            if (elem.innerHTML == "Fav")
                elem.innerHTML = "Unfav";
            else
                elem.innerHTML = 'Fav';
            }
    </script>
...
{% endfor %}

However the script seems to only load the last value of 'i', and so only the last link changes. Do I have to save it every time?

CodePudding user response:

Replace your code with this.

{% for i in objetos %}
...
<a onclick="change(this)" id="{{i.id}}">Fav</a>
...
{% endfor %}

<script>
    function change(e) {
        var elem = document.getElementById(e.getAttribute('id'))
        if (elem.innerHTML == "Fav")
            elem.innerHTML = "Unfav";
        else
            elem.innerHTML = 'Fav';
        }
</script>

Your actual rendered code is this.

...
<a onclick="change()" id="1">Fav</a>
    <script>
        function change() {
            var elem = document.getElementById("1");
            if (elem.innerHTML == "Fav")
                elem.innerHTML = "Unfav";
            else
                elem.innerHTML = 'Fav';
            }
    </script>
...

...
<a onclick="change()" id="2">Fav</a>
    <script>
        function change() {
            var elem = document.getElementById("2");
            if (elem.innerHTML == "Fav")
                elem.innerHTML = "Unfav";
            else
                elem.innerHTML = 'Fav';
            }
    </script>
...

...
<a onclick="change()" id="3">Fav</a>
    <script>
        function change() {
            var elem = document.getElementById("3");
            if (elem.innerHTML == "Fav")
                elem.innerHTML = "Unfav";
            else
                elem.innerHTML = 'Fav';
            }
    </script>
...

Inspect on browser. You will see this.

So when you click on first the last gets called as it matches the js function name. If you create multiple js function name with same name, last function would be use It's same as reassgning value Same way in your code the last function was getting called always. Hence was the issue.

  • Related