I just want to make the result of input 1 and input 2 appear in input 3 without clicking any button or text. It means if user write number 5 in input 1 and number 5 in input 2 will automatically show the result 10 in input 3. I have this code :
<div >
<div >
<label for="exampleInputEmail1" >number 1</label>
<input type="number" name="num1" id="num1" value="<?php echo
$num1?>" placeholder="0" aria-describedby="emailHelp">
</div>
<div >
<label for="exampleInputEmail1" >number 2</label>
<input type="number" name="num2" id="num2" value="<?php echo
$num2?>" placeholder="0" aria-describedby="emailHelp">
</div>
<div >
<label for="exampleInputEmail1" >result</label>
<input type="number" name="res" id="res" value="<?php echo
$res?>" placeholder="0" aria-describedby="emailHelp">
</div>
</div>
java script :
<script>
function myFunction() {
var x = parseInt(document.getElementById("num1").value);
var y = parseInt(document.getElementById("num2").value);
var z = x y;
document.getElementById("res").innerHTML = z;
}
</script>
CodePudding user response:
There are a few adjustments you need to do.
You need to call you function myFunction()
at the event oninput
, and you need to call it on the input <input>
fields not on the result <input>
field as you did it.
In myFunction()
you need to check whether a value could be parsed using isNaN()
. In case of a sum it's probably a good idea to set a default value of 0
in case some invalid value was entered or one field is empty.
function myFunction() {
var x = parseInt(document.getElementById("num1").value);
// set default value to 0 if parsing was not successful
if (isNaN(x)) x = 0;
var y = parseInt(document.getElementById("num2").value);
// set default value to 0 if parsing was not successful
if (isNaN(y)) y = 0;
var z = x y;
document.getElementById("res").value = z;
}
<div >
<div >
<label for="exampleInputEmail1" >number 1</label>
<input type="number" name="num1" id="num1" oninput="myFunction()" value="<?php echo
$num1?>" placeholder="0" aria-describedby="emailHelp" />
</div>
<div >
<label for="exampleInputEmail1" >number 2</label>
<input type="number" name="num2" id="num2" oninput="myFunction()" value="<?php echo
$num2?>" placeholder="0" aria-describedby="emailHelp" />
</div>
<div >
<label for="exampleInputEmail1" >result</label>
<input type="number" name="res" id="res" value="<?php echo
$res?>" placeholder="0" aria-describedby="emailHelp" />
</div>
</div>