【问题标题】:How to expose newly added select option to Javascript如何向 Javascript 公开新添加的选择选项
【发布时间】:2021-06-24 10:48:00
【问题描述】:

我在这方面花了一段时间,但找不到对我有意义的答案。并不是说没有 100 多个答案会有所帮助,我只是没有选择解决方案。

我在 jinja 模板中有一个选择字段,连接到 Python / Flask / SQLAlchemy 应用程序。如果有什么不同,我正在使用 Bootstrap 5。我才刚刚开始掌握 Javascript。

我的目标是:-

  • 从模板中,单击链接以打开 Bootstrap 5 模式 - 工作正常
  • 在模态表单中输入详细信息并保存详细信息 - 工作正常
  • 当我返回模板时 - 新条目显示为可选 选项 - 工作正常
  • 我还希望选择字段默认为 新添加的选项 - 不起作用(该字段保持空白)

经过调查,似乎新选项虽然在选择字段中可见,但对 Javascript 尚不可用。

选择字段的代码(基于 SQLAlchemy QuerySelect 字段):-

HTML(神社)

# I'm using wtforms so the id of this element is #individual_birth_location
<div class="col-sm-7 w-auto">
    {{ wtf.form_field(form.individual_birth_location, class='form-select w-auto') }}
</div>

Javascript

    <!--The 'btnaddlocation' button is the Save button on the modal-->
    document.getElementById('btnaddlocation').onclick = function() {
    var len = document.getElementById('individual_birth_location').length;      
    if (eventType === 'birth') {
        document.getElementById('individual_birth_location').value = len;
    } else if (eventType === "death") {
        <!-- similar code-->
    }
    }

我已经尝试将值设置为 len-1(即在新选项之前添加的选项)并且效果很好。

但是当我通过模态添加新记录时,模板似乎还不“知道”新记录。所以选择字段保持空白(即使新添加的选项清楚地在列表中)。

我错过了什么?

谢谢。

【问题讨论】:

    标签: javascript python jinja2 bootstrap-modal flask-sqlalchemy


    【解决方案1】:

    我不确定 python 但是

       <!--The 'btnaddlocation' button is the Save button on the modal-->
        document.getElementById('btnaddlocation').onclick = function() {
        var len = document.getElementById('individual_birth_location').length;      
         if (eventType = 'birth') { 
             document.getElementById('individual_birth_location').value = len;
         } else if (eventType = "death") {
             <!-- similar code-->
        }
        }
    

    您正在尝试的比较(假设)不是比较而是分配。 所以如果你想检查 eventType 是否等于'birth',javascript 看起来像这样:

    document.getElementById('btnaddlocation').onclick = function() {
    var len = document.getElementById('individual_birth_location').length;      
    if (eventType === 'birth') { 
        document.getElementById('individual_birth_location').value = len;
    } else if (eventType === "death") {
        <!-- similar code-->
    }
    }
    

    Source for comparison w3schools

    【讨论】:

    • 感谢 feho 的回复,我现在在问题中更正了。不幸的是我仍然有同样的问题。再次感谢您的回复。
    猜你喜欢
    • 2013-04-18
    • 2023-02-15
    • 2014-12-30
    • 2015-09-29
    • 1970-01-01
    • 2018-03-23
    • 2020-09-11
    • 2013-08-09
    • 1970-01-01
    相关资源
    最近更新 更多