Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
95 views
in Technique[技术] by (71.8m points)

How to pass parameter to javascript from Django template while using for loop

I am creating a quiz application using django. I am facing a problem in sending paramter to my javascript function from django template.

Html Code.

{% for qts in page %}

<input type="button" id ="btn-1" name="grp" value="{{qts.opt1}}" class="btn btn-outline-primary mt-3" onclick = "check(this,{{qts.answer}})">

Javascript Code

function check(btn,answer) {
   var user_ans_id = btn.id;
   var user_ans = document.getElementById(user_ans_id).value;
   console.log(answer);
}

Is there any other solution.

Thanks in Advance!

question from:https://stackoverflow.com/questions/65643236/how-to-pass-parameter-to-javascript-from-django-template-while-using-for-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A simpler and cleaner way of achieving the desired output can be implemented as follows using jquery

    {% for qts in page %}
    <input type="button" value="{{qts.opt1}}" class="quest-btn" data-answer="{{qts.answer}}" />
    {% endfor %}
    <script>
        $(".quest-btn").click((e) => {
            const targetElement = e.target;
            console.log(
                targetElement.dataset.answer,
                targetElement.value
            );
        });
    </script>

In the about code quest-class is just a dummy class to attach click event listener to multiple button you can use any common class in buttons.

to know more about jquery click event listener check this out

for more info about data-attributes check this


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...