0

I'm using spring mvc for my form which has the tag

<form:input type="number" class="value1" id="value1" path="commandName.object.field1" />
<form:input type="number" class="value1" id="value1" path="commandName.object.field2" />

<input type="text" disabled="disabled" id="result" />

I read some questions in regards to calculations and even found a js fiddle:

http://jsfiddle.net/g7zz6/1125/

how do i calculate 2 input fields and put results in 3rd input field

but it doesn't work when the input tag is form:input. Is it possible to do auto calculation of the 2 form:input fields upon keyin and update the 3rd input?

Community
  • 1
  • 1
Arnold Cristobal
  • 843
  • 2
  • 16
  • 36
  • What is the JS you're using? Also the output will be an `` element, just like the jsFiddle you linked to, so the logic should be identical – Rory McCrossan May 03 '17 at 07:53

3 Answers3

1

Here you go

HTML

<input type="text" class="input value1">
<input type="text" class="input value2 ">
<input type="text" disabled="disabled" id="result">

JS

$(document).ready(function(){
$('input[type="text"]').keyup(function () {
  var val1 = parseInt($('.value1').val());
  var val2 = parseInt($('.value2').val());
          var sum = val1+val2;
          $("input#result").val(sum);
});
});

Fiddle https://jsfiddle.net/1sbvfzcc/

Rtra
  • 514
  • 12
  • 25
0

$(document).ready(function(){
    var val1 = +$(".value1").val();
    var val2 = +$(".value2").val();
    $("#result").val(val1+val2);
});
$('.input').blur(function(){
    var val1 = +$(".value1").val();
    var val2 = +$(".value2").val();
    $("#result").val(val1+val2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="input value1" value="20">
<input type="text" class="input value2" value="30">
<input type="text" disabled="disabled" id="result">

Please check the code this might help you understand why your code is not working. You are using document ready function which is not able to get the value as no default value for input box. I have added a new blur function which will calculate the value on change of input box

ankit verma
  • 616
  • 5
  • 17
0

Try this your form tag syntax was wrong

$('form').on('keyup' ,'.value1', function(){
var k=0;
$('.value1').each(function(){
 k +=parseFloat($(this).val()|0);
})
$('input:text').val(k)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="number" class="value1" id="value1" path="commandName.object.field1" />
</form>
<form>
<input type="number" class="value1" id="value1" path="commandName.object.field2" />
</form>

<input type="text" disabled="disabled" id="result" />
prasanth
  • 22,145
  • 4
  • 29
  • 53