简体   繁体   English

如何使用下拉值过滤Django中显示的元素列表

[英]How to filter a list of displayed elements in django with a dropdown value

Right now I have a list of forms being displayed by Django: 现在,我有一个由Django显示的表单列表:

{% for form in forms %}
  <form method="post" class="{{ form.css_class }}"novalidate>
    {% csrf_token %}
    {% include 'bs4_form.html' with form=form %}
    <input type="hidden" name="selected_form" value="{{ forloop.counter0 }}">
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>
{% endfor %}

I also have a dropdown being rendered above the forms: 我还在表格上方显示了一个下拉列表:

<label>Choose a component to modify:
  <select class="rule-component" name="component">
    <option value="">Select One …</option>
    <option value="0">Option 0</option>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="4">Option 4</option>
  </select>
</label>

My question is, how would I go about displaying no form when the page is entered, and a single form that corresponds with the dropdown value when that is selected? 我的问题是,进入页面后,我将如何不显示任何表格,而选择下拉列表值时只显示一个表格呢?

I've attempted something with JavaScript, but I'm not very familiar with it and I'm not sure how to get this to interact with the django templating language. 我已经尝试使用JavaScript进行一些操作,但是我对它不是很熟悉,并且不确定如何使它与django模板语言进行交互。 The code below allows me to log the form element I want to display by linking it with the forloop.counter: 下面的代码允许我通过将其与forloop.counter链接来记录要显示的表单元素:

<script type="text/javascript">
const formElement = document.querySelector(".rule-component")

formElement.addEventListener('change', (event) => {
  const selectElement = document.querySelector("form input[value='" + formElement.value + "']").parentNode;
  console.log(selectElement)
  const result = document.querySelector('.result');
  result.textContent = `You like ${selectElement.className}`;
});
</script>```

I figured it out, was just some JavaScript that needed to be linked up to an array, 'ids' with the css_classes in the Django forms: 我发现,只是一些JavaScript需要链接到数组,即Django形式中的css_classes'ids':

<script type="text/javascript">
const ids=["jira-label", "label-rule-category"]
const dropDown = document.getElementById("rule-component");

dropDown.onchange = function() {
  for(var x = 0; x < ids.length; x++) {
    console.log(ids[x])
    document.getElementById(ids[x]).style.display = "none";
  }
  console.log(this.value)
  document.getElementById(this.value).style.display = "block";
}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM