【问题标题】:How get selected value in bootstrap V5 select with python如何使用 python 在引导 V5 选择中获取选定的值
【发布时间】:2022-01-08 11:57:40
【问题描述】:

我在 django 中使用Class Based Views... 那么我的模型是:

models.py

class Survey(Base):
    description = models.CharField('Description', max_length=50, unique=True)
    item1 = models.CharField('Item1', max_length=50)
    item2 = models.CharField('Item2', max_length=50)
...
    class Meta:
        verbose_name = 'Survey'

    def __str__(self):
        return self.description
    

现在我正在读取数据库数据以进行填充选择并且工作正常。

如何为填充表字段获取此选择项?

info.html

    <div class="col-12">
        <div class="card card-chart">
            <div class="card-header ">
                <div class="row">
                    <div class="col-sm-4 text-left">
                        <h2 class="card-title">Informations</h2>
                       
                        <option selected>choose a option</option>
                            {% for s in survey  %}
                                <option>{{s.description}}</option>
                            {% endfor  %}

                        </select>
                        
                    </div>
                    
                    <!-- of course, in this moment variable [s] not exist  -->
                    <div class="col-sm-8 text-right">
                        <table class="table">
                            <tbody>
                                <tr>
                                    <td>item 1</td>
                                    <td>item 2</td>
                                </tr>
                                <tr>
                                    <!-- want fill this fields with select item above-->
                                    <td>{{s.item1}}</td>
                                    <td>{{s.item2}}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                   
                </div>
            </div>
        </div>
    </div>

</div>

views.py

from django.views.generic import TemplateView
from .models import Survey

class IndexView(TemplateView):
    template_name = 'index.html'

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context['survey'] = Survey.objects.all()
        return context

【问题讨论】:

    标签: python django bootstrap-5


    【解决方案1】:

    您应该将 value 属性添加到您在 HTML 中创建的选项中。


    如果您想在其他地方使用该值,您可以按照以下步骤操作:

    您可以通过为 Select 元素提供特定的 id 并检索其值来获取它。

    你可以通过var el = document.getElementById("#id_of_select")获取元素。

    通过el.value可以得到select的选中值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-03
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多