Reputation: 5761
The following works partially:
function pvst(x,y){
return parseInt(x)/100 * parseInt(y);
}
var value1 = document.getElementById('v1').value,
value2 = document.getElementById('v2').value,
input_1 = document.getElementById('v1'),
input_2 = document.getElementById('v2');
function insertValue(){
var newSum = pvst(value1, value2);
if(isNaN(newSum) === true){
document.getElementById("test").innerHTML = 'only numbers!!';
}
else{
document.getElementById("test").innerHTML = newSum;
}
}
input_1.onkeyup = insertValue();
input_2.onkeyup = insertValue();
However the onkeyup is not working as expected. It suppose to update the newSum as soon as you type in. I can't figure out where I am doing wrong
Upvotes: 0
Views: 94
Reputation: 928
Try this:
function pvst(x, y) {
return parseInt(x) / 100 * parseInt(y);
}
function insertValue() {
var value1 = document.getElementById('v1').value;
value2 = document.getElementById('v2').value;
input_1 = document.getElementById('v1');
input_2 = document.getElementById('v2');
var newSum = pvst(value1, value2);
if (isNaN(newSum) === true) {
document.getElementById("test").value = 'only numbers!!';
}
else {
document.getElementById("test").value = newSum;
}
}
Sample HTML:
<input id="v1" type="text" onkeyup="insertValue();" />
<input id="v2" type="text" onkeyup="insertValue();" />
<input id="test" />
Upvotes: 0
Reputation: 27765
The problem I see that you invoke your functions instead of passing function handlers:
Use this (removed ()
):
input_1.onkeyup = insertValue;
input_2.onkeyup = insertValue;
instead of this:
input_1.onkeyup = insertValue();
input_2.onkeyup = insertValue();
If you will not do this your onkeyup
events will try to execute function result instead of executing function. And as you didn't return anything in insertValue
function they just get undefined
value and do nothing.
Update: As you store your values in variables they not updated each time after input was changed and use always same value, to look at values you need to get them again from DOM, so you need to do this:
var newSum = pvst(document.getElementById('v1').value, document.getElementById('v2').value);
So updated code from my side should look like this:
function pvst(x,y){
return parseInt(x)/100 * parseInt(y);
}
var input_1 = document.getElementById('v1'),
input_2 = document.getElementById('v2');
function insertValue(){
var newSum = pvst(input_1.value, input_2.value);
if(isNaN(newSum) === true){
document.getElementById("test").innerHTML = 'only numbers!!';
} else {
document.getElementById("test").innerHTML = newSum;
}
}
input_1.onkeyup = insertValue;
input_2.onkeyup = insertValue;
Upvotes: 2