简体   繁体   English

无法使用JavaScript中的onload()访问表单元素

[英]Can't access form elements with onload() in JavaScript

I'm putting together dependent drop-downs (Teacher -> Class -> Student) and am having issues with setting the initial state of the drop-downs. 我将相关的下拉菜单(老师->课堂->学生)放在一起,并且在设置下拉菜单的初始状态时遇到问题。 Here's the code: 这是代码:

edit_contract.html edit_contract.html

{% load crispy_forms_tags %}    
<div>
    <form method="post" id="contractForm" novalidate 
        data-teachers-url="{% url 'wakemeup:ajax_load_teachers' %}" 
        data-classes-url="{% url 'wakemeup:ajax_load_classes' %}" 
        data-students-url="{% url 'wakemeup:ajax_load_students' %}" 
    >
        {% crispy form %}
    </form>
</div>

<script>
    // Update class drop-down when teacher changes
    $("#id_teacheruserid").change(function () {
        update_classes($(this))
      });

    // Update students drop-down when class changes
    $("#id_classid").change(function () {
        update_students($(this))
      });

    function update_teachers() {
        // Get form values
        var url = $("#contractForm").attr("data-teachers-url");
        var contractId = $(document.getElementById("id_contractid")).val();

        $.ajax({                             // initialize AJAX request
          url: url,                         
          data: {
            'contractid': contractId
          },
          success: function (data) {            
            $("#id_teacheruserid").html(data);  // Update "teacheruserid" field
          }
        })

        update_classes(); // Update classes drop-down
    };

    function update_classes() {
        // Get form values
        var url = $("#contractForm").attr("data-classes-url");
        var teacherUserId = $(document.getElementById("id_teacheruserid")).val();
        var contractId = $(document.getElementById("id_contractid")).val();

        $.ajax({                            // initialize AJAX request
          url: url,                         
          data: {
            'teacheruserid': teacherUserId, 
            'contractid': contractId
          },
          success: function (data) {        
            $("#id_classid").html(data);       // Update "classid" field
          }
        })

        update_students(); // Update students drop-down
    };

    function update_students() {
        // Get form values
        var url = $("#contractForm").attr("data-students-url");
        var classId = $(document.getElementById("id_classid")).val();
        var contractId = $(document.getElementById("id_contractid")).val();

        $.ajax({                                // initialize AJAX request
          url: url,                                 
          data: {
            'classid': classId,                     
            'contractid': contractId
          },
          success: function (data) {                
            $("#id_partyuserinfo").html(data);      // Update "partyuserinfo" field
          }
        })
    };

    window.onload = function() {
        // Initial load of drop-down menus
        update_teachers(); // Cascades to update_classes() and update_students()
    };      
</script>

Flow summary 流程摘要

update_teacher() update_teacher()
- update HTML (drop-down options) for "id_teacheruserid" field -更新“ id_teacheruserid”字段的HTML(下拉选项)

update_classes() update_classes()
- read value from "id_teacheruserid" field (undefined for initial load) -从“ id_teacheruserid”字段读取值(初始加载时未定义)
- update HTML (drop-down options) for "id_classid" field -更新“ id_classid”字段的HTML(下拉选项)

update_students() update_students()
- read value from "id_classid" field (undefined for initial load) -从“ id_classid”字段读取值(初始加载时未定义)
- update HTML (drop-down options) for "id_partyuserinfo" field -更新“ id_partyuserinfo”字段的HTML(下拉选项)

The problem 问题

The problem I'm seeing is that the script can't access the values in the form fields in the onload() call. 我看到的问题是脚本无法访问onload()调用中的表单字段中的值。 For example, this line in update_classes() : 例如, update_classes()这一行:

    var teacherUserId = $(document.getElementById("id_teacheruserid")).val();

I added an alert(teacherUserId) directly after this line. 我在此行之后直接添加了一个alert(teacherUserId) On initial page load, it returns undefined . 在初始页面加载时,它返回undefined However, when I select a different value from the teacher drop-down, the alert displays the expected value. 但是,当我从教师下拉菜单中选择其他值时,警报将显示预期值。

My guess is that in the initial onload() , the referenced field values/options (ie id_teacheruserid ) have not been loaded or made available yet. 我的猜测是,在初始的onload() ,引用的字段值/选项(即id_teacheruserid )尚未加载或可用。 The fields themselves exist, but return undefined values. 字段本身存在,但返回undefined值。 Once this function completes, though, it seems they are then accessible and the menus behave as expected. 但是,一旦完成此功能,似乎可以访问它们并且菜单的行为与预期的一样。

How can I run update_teachers() to do the initial load and have it access the form field values? 如何运行update_teachers()进行初始加载并使其访问表单字段值?

First of all you can use 首先你可以使用

$("#id_teacheruserid").val();

instead of 代替

$(document.getElementById("id_teacheruserid"))

Second 第二

you need to grab the option selected value from the dropdown 您需要从下拉列表中选择选项选择的值

$("#id_teacheruserid").find(":selected").val() 

to get the selected ID 获取选定的ID

Third, you need to call next drop down fill function on success callback 第三,您需要在成功回调中调用next下拉填充功能

$.ajax({                             // initialize AJAX request
          url: url,                         
          data: {
            'contractid': contractId
          },
          success: function (data) {            
            $("#id_teacheruserid").html(data);  // Update "teacheruserid" field
             update_classes();
          }
        })

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

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