【问题标题】:Getting selected element of python list获取python列表的选定元素
【发布时间】:2020-07-04 09:21:28
【问题描述】:

我有一个包含 6 个元素的列表。我通过bootstrap-select 将其作为下拉列表获取。只有提交表单进行处理,我才能在控制台中接收列表元素。

主要问题是:

如何使当我选择一个元素时,我可以在提交表单之前立即在控制台中获取(打印)它?

app.py

description = ['one','two','three','four','five','six']

@app.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        docs = request.form.getlist('sel')
        print(docs)
        return render_template('login.html', description=description)
    return render_template('login.html', description=description)

login.html

      <form action="" method="POST" class="form-inline">
        <select id='sel' name='sel' class="selectpicker" multiple data-live-search="true">
          {% for desc in description %}
            <option value="{{desc}}">{{desc}}</option>
          {% endfor %}
        </select>
        <button type="submit" class="btn btn-primary">Identify</button>
      </form>

  <script type="text/javascript">
    $('select').selectpicker();
  </script>

【问题讨论】:

    标签: python html python-3.x flask


    【解决方案1】:

    如果您想在控制台中打印,则无需使用 app.py,但是,您需要使用 login.html

    要启用此功能,您的答案是 onchange,这是为 &lt;select&gt; 预定义的,当您选择一个选项时会捕获您的数据。也不需要提交按钮。

    更新答案: &lt;p&gt; 等待值,该值在我们的函数 printValue() 中设置

    <select id='sel' name='sel' class="selectpicker" multiple data-live-search="true" onchange="printValue(this)">
       {% for desc in description %}
          <option value="{{desc}}">{{desc}}</option>
       {% endfor %}
    </select>
    <p id="mySelectedValue" style="margin-top: 10px;"></p>
    
    
    
    <!-- In your script, call your function, which prints the data in your console-->
    <script type="text/javascript">
        function printValue(selectedItem){
           $('#mySelectedValue').html(selectedItem.value);
        }
    </script>
    

    printValue() 方法中,您使用方法:) 打印数据值。您可以在此处执行任何操作,例如将所选项目添加到您的数组或地图中。这取决于,我们只是为了满足要求而在控制台中打印:)

    这是关于 onchange 如何在 SELECT 中工作的参考的 SNIPPET。

    function printValue(selectedItem){
      console.log(selectedItem.value);
    }
    <select class="form-control" id="your_id" onchange="printValue(this)">
         <option value="Value1" selected>Value1</option>
         <option value="Value2">Value2</option>
         <option value="Value3">Value3</option>
    </select>

    【讨论】:

    • 能否请您说明如何在 html 页面上获取它?
    • 我已经在代码中向你展示了@abby。代码中有什么不明白的地方?
    • 或者你想在HTML Page而不是console.log()中显示所选项目,这是你的问题@abby?
    • 是的。我想在您的 HTML 页面中显示所选项目,而不是 console.log()
    • @abby,我已经更新了答案,请确保您在HTML file 中导入了JQuery,否则,使用此$('mySelectedItem').html() 会出错。 Cos, '$' 用于使用jQuery 调用项目。如果你得到了你想要的东西,你可以标记这个答案,并给它投票,这样人们就可以在他们提出你的问题时找到正确的答案:)
    猜你喜欢
    • 2023-03-08
    • 2019-03-03
    • 1970-01-01
    • 2016-01-14
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多