首页 > 解决方案 > 如何使用 javascript 获取 {{form}} 值?

问题描述

有一段我的html代码:

 <!-- STEP 1: class .active is switching steps -->
  <div data-step="1" class="">
    <h3>Załóż fundację:</h3>
    <div class="form-group form-group--inline">
      <label> Nazwa <input type="text" name="name" id="name" /> </label>
      <label> Opis <input type="text" name="description" id="description" /> </label>
    </div>
    <div class="form-group form-group--buttons">
      <button type="button" class="btn next-step">Dalej</button>
    </div>
  </div>

      <!-- STEP 2 -->
      <div data-step="2">
        <h3>Podaj typ fundacji</h3>
        <div class="form-group form-group">
          {{form1}}
        </div>
        <div class="form-group form-group--buttons">
          <button type="button" class="btn prev-step">Wstecz</button>
          <button type="button" class="btn next-step">Dalej</button>
        </div>
      </div>

在第 1 步中,我可以通过 id 从输入中获取值,例如:

var name = document.getElementById('name').value;

我怎么能用 {{form1}} 做这样的事情,它是一种选择字段:

class AddFundationTypeForm(forms.Form):
    type = forms.ChoiceField(choices=type_of_organization) 

type_of_organization 是一个字典,有 3 个键值对。

标签: javascripthtml

解决方案


id_ 您可以通过为您的类型字段添加前缀来对任何表单字段执行此操作:

var type = document.getElementById('id_type').value;

django 默认使用为每个字段生成 id'id_'+ your_field_name

并且您想获得完整的表格,那么您应该在您的template.html

模板

<form id="myForm" action="" method="post">
    {{form1}}
</form>

然后在javascript中:

var form = document.getElementById('myForm')

推荐阅读