在django模板中不会以形式监听keyup事件

时间:2017-12-08 14:09:53

标签: javascript jquery python django

我第一次使用javascript和django。在我的表格中,我需要通过计算两个字段来显示基本金额,即数量和费率。为此,我做了以下

{% block content %}
<div class="right_col" role="main">
    <h1 class="text-center"> Purchase Order</h1>
    <div class="space"></div>
    <!-- {%include 'includes/form.html'%} -->
    {%include 'dashboard/purchase_order/purchase_order_form.html'%}
</div>
{% endblock content %}

{% block javascripts %}
  {{ block.super }}
  <script>
    $(document).ready(function() {
      console.log('dom is ready');
      $('#form-change').keyup(function() {
        console.log('form')
        var quantity = document.getElementById('id_quantity').value;
        var rate = document.getElementById('id_rate').value;
        if (quantity && rate) {
          document.getElementById('id_basic_amount').value = parseInt(quantity) * parseInt(rate);
        }
      })
    })
  </script>
{% endblock javascripts %}


<form id="demo-form2 form-change" class="form-horizontal form-label-left" action="" method="post" enctype="multipart/form-data">
   {% csrf_token %}
   <div class="form-group">
      <div class="col-md-6 col-sm-6 col-xs-12">
         <input type="number" name="quantity" value="0" min="0" class="form-control col-md-7 col-xs-12" required="" id="id_quantity">
      </div>
   </div>
   <div class="form-group">
      <div class="col-md-6 col-sm-6 col-xs-12">
         <input type="number" name="rate" value="0.0" step="0.01" class="form-control col-md-7 col-xs-12" required="" id="id_rate">
      </div>
   </div>
   <div class="form-group">
      <div class="col-md-6 col-sm-6 col-xs-12">
         <input type="number" name="basic_amount" value="0.0" step="0.01" class="form-control col-md-7 col-xs-12" required="" id="id_basic_amount">
      </div>
   </div>
</form>

但是没有收听keyup事件。行console.log('dom is ready')显示在控制台中,但行console.log('form')未在控制台中进行安慰。我在jsbin中尝试了单独的javascript,并且它正在工作

http://jsbin.com/hadafezeqa/edit?html,console,output

为什么它只在django模板中工作?

1 个答案:

答案 0 :(得分:0)

尝试将keyup事件绑定到其中一个表单元素,而不是表单本身。 尝试更改表单的输入,如下所示:

 <input type="number" name="quantity" value="0" min="0" class="form-control col-md-7 col-xs-12 form-change" required="" id="id_quantity">

<input type="number" name="rate" value="0.0" step="0.01" class="form-control col-md-7 col-xs-12 form-change" required="" id="id_rate">

$('#form-change').keyup()更改为$('.form-change').keyup()

希望你能看到控制台。

OR

更改表单的ID。

<form id="demo-form2 form-change">

要:

<form id="form-change">