简体   繁体   中英

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:

{% 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. The code below allows me to log the form element I want to display by linking it with the 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:

<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>

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.

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