根据基于JQuery

时间:2019-03-27 16:35:07

标签: jquery wordpress contact-form-7

我正在构建一个表单,用户应在其中键入数字并在复选框中选择选项。最后,我想根据输入进行计算并将其显示给用户。我找到了一个指导我朝正确方向here的教程。 这样,我就可以根据用户的输入值进行简单的计算。 现在,我想根据选中的复选框数量进行更复杂的计算。在我的代码中,我有字段“ 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。

关于如何实现这一目标的任何想法?它并不一定需要响应。要在按钮上开始计算,也可以。

1 个答案:

答案 0 :(得分:0)

我会这样编写您的函数,然后在代码段代码之前将其分解:

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" />

相关问题