如何“加载”依赖于页面加载的下拉列表? [英] How to "load" dependent drop down upon page load?

查看:68
本文介绍了如何“加载”依赖于页面加载的下拉列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有从属下拉列表的表格。只要所选的主要选项没有任何辅助选项,并且在首次加载页面时,该辅助下拉菜单都将隐藏。每当提交表单时,由于大多数情况下下拉列表保持不变,因此仅清除第一个字段,但是,由于只要主下拉列表发生更改,脚本都可以工作,因为加载并不构成更改,它只是将选择/提交的选项保留在主下拉菜单中,并且即使选择的主选项确实具有辅助选项,也只会显示一个空的辅助下拉列表。我从一个教程的下拉菜单中获得了大部分JS,因为我不太熟悉它。为了更直观地理解:

I have a form with a dependent drop-down. This secondary drop-down is hidden whenever the primary option selected does not have any secondary options, and when the page first loads. Whenever the form is submitted, only the first field gets cleared out, since most of the time the drop-downs remain the same, however, since the script works whenever there is a change in the primary drop-down, since the load upon does not constitute a change, it just keeps the selected/submitted option on the primary drop-down, and will just display an empty secondary drop-down, even when the primary option selected does have secondary options. I got most of the JS from the drop-down from a tutorial, as I am not very familiar with it. For a more visual understanding:

这是页面首次加载时的形式

This is the form when the page first loads

当您选择具有次要选项的选项时,将显示另一个下拉列表

When you select an option that has secondary options, the other dropdown appears

在选择了工作站并提交后,员工编号将清除,但是其他两个应该保留,但是,当页面在提交时重新加载时,看起来像这样,并且由于技术上没有任何内容,因此已根据调试器清除了该站。我不是很在意站点清理,而是更多地是没有一个不应该为空的空下拉菜单。

After you select a Station and submit, the Employee # clears, but the other two are supposed to remain, however, when the page reloads upon submission, it looks like this, and the station has been cleared according to the debugger since there are none technically. I don't care so much about the station clearing, but more about not having an empty drop-down that should not be empty.

当我查看保留在表单中的数据时,只保留了工作区,因为在选择其他选项之前,依赖项下拉列表不会加载从下拉菜单中,如果您想再次看到Box Assembly选项,则必须单击另一个选项,然后返回Box Assembly(例如)

And when I look at the data that remained in the form, only the work area stayed, because the dependent dropdown does not load until you select another option from the drop down, and if you wanted to be able to see the Box Assembly options again, you'd have to click another option and then go back to Box Assembly (for example)

如何解决此问题?有没有一种方法可以强制javascript首先尝试加载,以便它检查剩余的选项是否确实具有次要选项,无论它是否已被触发?

How could I fix this issue? Is there a way to force the javascript to attempt to load first so that it checks if the option that remained does have the secondary options, whether it has been triggered or not?

forms.py

class WarehouseForm(AppsModelForm):
    class Meta:
        model = EmployeeWorkAreaLog
        widgets = {
            'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}),
        }
        fields = ('employee_number', 'work_area', 'station_number')


    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['station_number'].queryset = Station.objects.none()

        if 'work_area' in self.data:
            try:
                work_area_id = int(self.data.get('work_area'))
                self.fields['station_number'].queryset = Station.objects.filter(work_area_id=work_area_id).order_by('name')
            except (ValueError, TypeError):
                pass
        elif self.instance.pk:
            self.fields['station_number'].queryset = self.instance.work_area.stations.order_by('name')

views.py

def enter_exit_area(request):
    enter_without_exit = None
    exit_without_enter = None

    if request.method == 'POST':
        form = WarehouseForm(request.POST)
        if form.is_valid():
            emp_num = form.cleaned_data['employee_number']
            area = form.cleaned_data['work_area']
            station = form.cleaned_data['station_number']

            # Submission logic
                form = WarehouseForm(initial={'employee_number': '', 'work_area': area, 'station_number': station})

    else:
        form = WarehouseForm()
    return render(request, "operations/enter_exit_area.html", {
        'form': form,
        'enter_without_exit': enter_without_exit,
        'exit_without_enter': exit_without_enter,
    })

urls.py

urlpatterns = [
    url(r'enter-exit-area/$', views.enter_exit_area, name='enter_exit_area'),

    path('ajax/load-stations/', views.load_stations, name='ajax_load_stations'),
]

此html末尾是处理相关下拉菜单的脚本

At the end of this html is the script that handles the dependent drop-down

enter_exit_area .html

{% extends "operations/base.html" %}
{% block main %}
    <form id="warehouseForm" action="" method="POST" data-stations-url="{% url 'operations:ajax_load_stations' %}" novalidate >
        {% csrf_token %}

        <div>
            <div>
                <label>Employee #</label>
                {{ form.employee_number }}
            </div>

            <div>
                <label>Work Area</label>
                {{ form.work_area }}
            </div>
            <div class="col-xs-8" id="my-hidden-div">
                <label>Station</label>
                {{ form.station_number }}
            </div>
        </div>
    </form>

    <script>
        function loadStations() {
            var url = $("#warehouseForm").attr("data-stations-url");
            var workAreaId = $(this).val();
            var $stationNumberField = $("#{{ form.station_number.id_for_label }}");

            $.ajax({
                url: url,
                data: {
                    'work_area': workAreaId
                },
                success: function (data) {
                    $("#my-hidden-div").show(); // show it
                    $stationNumberField.html(data);
                    // Check the length of the options child elements of the select
                    if ($stationNumberField.find("option").length === 1) {
                        $stationNumberField.parent().hide(); // Hide parent of the select node
                    } else {
                        // If any option, ensure the select is shown
                        $stationNumberField.parent().show();
                    }
                }
            });
        }
        $("#id_work_area").change(loadStations);
        $(document).ready(loadStations);
     </script>
{% endblock main %}

station_number_dropdown_options.html

<option value="">---------</option>
{% for station in stations %}
<option value="{{ station.pk }}">{{ station.name }}</option>
{% endfor %}


推荐答案

您有 $(document).ready(loadStations);

但是问题在于 loadStations ,您可以执行 var workAreaId = $(this).val();

But the problem is that in loadStations, you do var workAreaId = $(this).val();.

将是文档 $(document).val ()是一个空字符串。

this will be document, and $(document).val() is an empty string.

loadStations 中将选择器硬编码为:

Either hardcode the selector in loadStations:

// var workAreaId = $(this).val();
var workAreaId = $("#id_work_area").val();

或触发元素的更改:

$("#id_work_area").change(loadStations);
// $(document).ready(loadStations);
$("#id_work_area").change();

这篇关于如何“加载”依赖于页面加载的下拉列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆