gpt4 book ai didi

javascript - django/javascript/jquery/html/css : summing the contents of a form for display

转载 作者:太空宇宙 更新时间:2023-11-03 18:51:15 24 4
gpt4 key购买 nike

我要为网页构建一个 django 表单,允许用户输入两个数字:

    <form action="blah" method="post">
{% csrf_token %}
number1:
<input type="number" name="number1" value="{{ number1 }}" />
number2:
<input type="number" name="number2" value="{{ number2 }}" />

<input type="submit" value="Submit" />

在页面的其他地方,我想在用户输入这两个数字时显示它们的乘积。最有效的方法是什么?


编辑(2):我能够通过对提供的代码进行轻微修改来使一切正常工作:

{% if [test] %} 


<div style="padding-top: 10%; padding-left: 12%">
<div class="row-fluid" >
<div class="span10 hero-unit" >

...

</div>
</div>
</div>

{% else %}

<div style="padding-top: 10%; padding-left: 20%;">
<div class="row-fluid" style="vertical-align: middle">
<div class="span8 hero-unit">

...

<form action="/" method="post">
{% csrf_token %}
{% if next %}
<input type="hidden" name="next" value="{{ next }}" />
{% endif %}
<div class="question"><<Question1>>
<input type="number" class="pull-right" name = "question1" value="{{ question1 }}" />
</div>
<br>
<div class="question"><<Question2>>
<input type="number" class="pull-right" name="question2" value="{{ question2 }}" />
</div>
<br>
<div style="padding-right: 10%">
<input type="submit" class="btn btn-primary button-text pull-right" value="Submit" />
</div>
<div id="product_output_container" style="padding-left: 10%;font-weight: bold" ></div>

<br>
</form>

</div>
</div>
</div>

{% endif %}

<!-- jquery -->

<script type="text/javascript">
$(document).ready(
function(){

var refreshProduct = function(){

var question1 = parseInt($('[name="question1"]').val(),10);
var question2 = parseInt($('[name="question2"]').val(),10);

var product = question1 * question2;

var product_container = $('#product_output_container');
if (!isNaN(product)){
product_container.text(product)
}
else{
product_container.text("")
}
}

$('[name="question1"]').keyup(refreshProduct);
$('[name="question2"]').keyup(refreshProduct);
}
);
</script>


{% endblock %}

最佳答案

将一个 jquery keyup 事件附加到您的每个输入。让事件将两个输入相乘并将总和放入输出元素。

$('form input.pull-right').keyup(function() {
var $inputs = $('form input.pull-right');
var product = 1;
for (var i = $inputs.length; i > 0; i--) {
product *= parseInt($inputs[i].val());
}
$('form input.output').val(total);
}

这是关于 jquery 的 keyup 的文档, selectorsval .

顺便说一句,如果您添加更多输入(右拉类),此代码将起作用。代码循环遍历它们..

关于javascript - django/javascript/jquery/html/css : summing the contents of a form for display,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14890799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com