I have a template in Django with a foor loop that looks roughly like this:
{% if items %}
<form method="post" name="managerform" id="managerform" action="">{% csrf_token %}
{{ managerform }}
</form>
{% for item in items %}
<script type='text/javascript'>
var yes = function yes() { manager(function(response) {
if(response && response.status == 'user') {
var object = '{{ item }}'
document.managerform.item.value = object;
document.managerform.preferences.value = "Yes";
document.managerform.submit();
}
else{
authUser(); } });}
</script>
...
<button onclick=yes()>Yes</button>
...
{% endfor %}
Which submits the form, the problem is it always submits the last item
from items
. I've tried making yes
take an argument, aitem
, which didn't help because using <button onclick=yes("{{item}}")>
failed entirely and doing:
<script>
aitem="{{ item }}"
</script>
<button onclick=yes(aitem)>
just uses the last item
from items
again.
Is there an obvious solution to this to anyone?
Change your button's HTML to be:
<button onclick='yes("{{item}}");'>Text</button>
And take out the <script>
code completely outside of your django conditionals and loops so that it is always available, but change it to be:
var yes = function (item) {
manager(function (response) {
if (response && response.status == 'user') {
var object = item;
document.managerform.item.value = object; // You could combine this and the previous line
document.managerform.preferences.value = "Yes";
document.managerform.submit();
} else {
authUser();
}
});
}
This way, the only thing inside of your django for
loop is the button, and each one ends up having a different argument for the yes
function. The yes
function now accepts a parameter and uses it like you wanted. You'll probably have to modify this to fit your needs though, because your code snippet seems like an example and is not exactly what you have.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.