首页 > 解决方案 > 基于 JQuery 在 Contact-Form-7 中选中的复选框数量计算

问题描述

我正在构建一个表单,用户应该在其中输入数字并在复选框中选择选项。最后,我想从输入中进行计算并将它们显示给用户。我在这里找到了一个指导我正确方向的教程。这样我就可以根据用户的输入值进行简单的计算。现在我想根据选中的复选框数量进行更复杂的计算。在我的代码中,我有字段“number”、“group1”、“group2”。结果应显示在“复杂数学”下。

这是到目前为止的表单代码:

<label>
  number: 
</label>
[number sample id:no min:1 max:1000]

<label>
group1:
</label>
[checkbox group1 id:g1 "p1" "p2" "p3"]

<label>
group2:
</label>
[checkbox group2 id:g2 "t1" "t2" "t3"]

<label>
simple math: 
</label>
[text test1 id:simple]
<label>
complex math: 
</label>
[text test2 id:complex]


<script>
jQuery(document).ready(function(){
var no;
var g1;
var g2;
var simple;
var complex;
jQuery("#no").on("change", function() {
 no= this.value ;
 simple=no*10;
 jQuery("#simple").val(simple.toFixed()); 
});
});
</script>

我喜欢实现的是复杂数学=(number*group1*30)+(number*group2*100)之类的计算。

所以对于 number=2 ,g1=2xchecked,g2=2xchecked 的结果应该是 520。

关于如何实现这一目标的任何想法?它不一定是响应式的。单击按钮开始计算也可以。

标签: jquerywordpresscontact-form-7

解决方案


我会这样写你的函数,我会在代码片段之前分解它:

var calc = function() {
  var no = $('#no').val();
  var g1 = $('input[name="g1"]:checked').val();
  var g2 = $('input[name="g2"]:checked').val();

  var simple = no * 10;
  $('#simple').val(simple.toFixed());

  var complex = (no * g1 * 30) + (no * g2 * 100);
  $('#complex').val(complex.toFixed());
}

$('#no, input[name="g1"], input[name="g2"]').on('change', function() {
  calc();
});

除非您需要,否则我认为不需要在计算之外存储实际值。由于没有提交按钮,因此仅在数字更改时更新计算值,而在任何输入更改时更新计算值是没有意义的。每当用户更改输入时执行的单个计算函数更有意义。然后就是让各个值在计算中使用。由于复杂的公式,我假设这些组实际上应该是单选按钮。

var calc = function() {
  var no = $('#no').val();
  var g1 = $('input[name="g1"]:checked').val();
  var g2 = $('input[name="g2"]:checked').val();
  
  var simple = no * 10;
  $('#simple').val(simple.toFixed());

  var complex = (no * g1 * 30) + (no * g2 * 100);
  $('#complex').val(complex.toFixed());
}

$('#no, input[name="g1"], input[name="g2"]').on('change', function() {
  calc();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label>number:</label>
<input id="no" type="number" min="1" max="1000" />

<br />

<span>group1:</span>
<label><input name="g1" type="radio" value="1" checked />p1</label>
<label><input name="g1" type="radio" value="2" />p2</label>
<label><input name="g1" type="radio" value="3" />p3</label>

<br />
<span>group2:</span>
<label><input name="g2" type="radio" value="1" checked />t1</label>
<label><input name="g2" type="radio" value="2" />t3</label>
<label><input name="g2" type="radio" value="3" />t3</label>

<br />

<label>simple math: </label>
<input id="simple" type="text" />

<br />

<label>complex math: </label>
<input id="complex" type="text" />


推荐阅读