仅当通过复选框选择文件时,Django 模板中的显示按钮

Show button in Django template only when the file is selected through check box?

本文关键字:Django 按钮 显示 复选框 文件 选择      更新时间:2023-09-26

我在 Django 模板中动态获取复选框,如下所示:

 <td><input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /></td>
              <td><label for="choice{{ forloop.counter }}">{{ choice.file_name }}</label></td>

有一个像这样的取消共享按钮:

<button>Unshare</button>

我想仅在用户单击复选框时显示Unshare按钮。

首先,

在模板中添加更多 id,以便您可以识别元素。

<table id="choices">
{% for choice in choices %}
    <td><input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /></td>
    <td><label for="choice{{ forloop.counter }}">{{ choice.file_name }}</label></td>
{% endfor %}
</table>

然后给按钮一个 id 和一个内联样式 -

<button id="unshare_button" style="display: none;">Unshare</button>

然后使用以下 javascript(只要其中任何一个显示按钮单击复选框 - 如果未选中,则不会隐藏按钮)。

var choices_table = document.getElementByID('choices');
var checkboxes = choices_table.getElementsByTagName('input');
var unshare_button = document.getElementByID('unshare_button');
for (var i = checkboxes.length; i > 0; i--) {
    checkboxes[i].addEventListener('click', function() {
        unshare_button.style.display = 'inline';
    }
}

恐怕我没有检查过这段代码,但它应该给你一个想法。