php – Sum two input values in realtime-ThrowExceptions

Exception or error:

I want to sum two different inputs in a third realtime variable. I will explain better what I want:

1 variable : 100 (input)

2 variable : 150 (input)

sum : 250 (not input)

How can I do this?

How to solve:

For realtime operations that is based on the client side events are managed by JavaScript and not PHP, which is server side. So to do something like what you wanted, we can use a keyboard event like keyup and make the third one readonly:

$(function () {
  $("#id-1, #id-2").keyup(function () {
    $("#id-3").val(+$("#id-1").val() + +$("#id-2").val());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="id-1" />
<input type="number" id="id-2" />
<input type="number" id="id-3" readonly />

Answer:

Here is also a version in plain javascript:

    <!doctype html>
<html>
<head>
</head>
<body>

<input type="text" id="val1">
<input type="text" id="val2">
<input type="button" value="Calculate" onclick="calculate();">
<script>

function calculate(){

var val1 = document.getElementById('val1').value;
var val2 = document.getElementById('val2').value;
var res = (parseFloat(val1)+parseFloat(val2))

alert(res);

}


</script>

Answer:

I would anyday recommend not using client side to handle such use cases but if you need to get it done using JS(JQuery), have a look below:

If HTML:

<input class="one" type="number" />
<input class="two" type="number" /> 

<p class="result"></p>

then JQuery should be:

$(".one, .two").keyup(function() {
  if($('.one').val() != "" && $('.two').val() != "") {
    var result = parseInt($('.one').val()) + parseInt($('.two').val());
    $('.result').text(result);
  }
});
$(".one, .two").keyup(function() {
  if($('.one').val() != "" && $('.two').val() != "") {
    var result = parseInt($('.one').val()) + parseInt($('.two').val());
    $('.result').text(result);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="one" type="number" />
<input class="two" type="number" /> 

<p class="result"></p>

Answer:

$(".one, .two").keyup(function() {
  if($('.one').val() != "" && $('.two').val() != "") {
    var result = parseInt($('.one').val()) + parseInt($('.two').val());
    $('.result').text(result);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="one" type="number" value="2" />
<input class="two" type="number" value="5"/> 

<p class="result"></p>

Leave a Reply

Your email address will not be published. Required fields are marked *