Onchange在select HTML中不起作用(Django)



我有一个问题模型。

My Modelsmodels.py

class Problems(models.Model):
Easy = 'Easy'
Medium = 'Medium'
Hard = 'Hard'
NA = 'NA'
DIFFICULTY = [
(NA, 'NA'),
(Easy, 'Easy'),
(Medium, 'Medium'),
(Hard, 'Hard'),
]
....
name_problem = models.CharField(max_length=150)
difficulty = models.CharField(max_length=150, choices=DIFFICULTY, default=NA)
....

我已经连接了django-filter

Myfilters.py

class ProductFilter(django_filters.FilterSet):
Easy = 'Easy'
Medium = 'Medium'
Hard = 'Hard'
NA = 'NA'
DIFFICULTY = [
(NA, 'NA'),
(Easy, 'Easy'),
(Medium, 'Medium'),
(Hard, 'Hard'),
]
name_pr = django_filters.CharFilter(field_name='name_problem', lookup_expr='icontains')
diff = django_filters.ChoiceFilter(field_name='difficulty' ,choices=DIFFICULTY)
class Meta:
model = Problems
fields = ['name_pr', 'diff']

Myviews.py

from .models import Problems
from .filters import ProductFilter
class MyProblemView(View):
def get(self, request):
problems = Problems.objects.all()
filter = ProductFilter(request.GET, queryset=problems)
problems = filter.qs
context = {
'problems': problems,
'filter': filter,
}
return render(request, 'problems/problems.html', context)

最后是html

{% load static %}
{% load widget_tweaks %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<form action="/" name="form" method="get">
{{ filter.form.diff }}
<input type="submit" />
</form>
</div>
{% for problem in problems %}
<p id="text"> {{ problem.name_problem }}
</p>
{% endfor %}
</body>
</html>

当表单中有按钮时,它会工作

但是我希望它没有按钮可按。我对JavaScript一点也不精通。所以我写了一个简单的函数在HTML SELECT上使用,但它不起作用。

<div class="container">
<form action="/" name="form" method="get">
{% render_field filter.form.diff name='formsel' onchange='fav()' %}
<input type="submit" />
</form>
</div>

{% for problem in problems %}
<p id="text"> {{ problem.name_problem }}
</p>
{% endfor %}
<script>
function fav() {
document.getElementById("text").innerHTML = form.formsel[form.formsel.selectedIndex].text
}
</script>  

可以这样配置ChoiceFilter,它知道onchange需要触发的JS函数。在你的代码中它可以是像

这样的东西
diff = django_filters.ChoiceFilter(field_name='difficulty' ,choices=DIFFICULTY, widget=forms.Select(attrs={'onchange': 'fav();'}))

[你可以使用fav(this.value),如果有提供选定的选择值给JS函数,但这里不需要]。模板中不需要任何特定的内容。

最后,JavaScript可能不需要更改所选索引,我猜它已经完成了。你需要的是提交表单(这就是我所理解的,当你写"当表单中有一个按钮时,它工作")。我不确定你是否需要为此编写一个JS函数,因为它只调用另一个函数,但如果你这样做,那将是类似

的东西

function fav() {document.getElementByName("form").submit();}

相关内容

  • 没有找到相关文章

最新更新