Evaluation maths expressions in JavaScript strings
I have two text boxes on my Form. One is txtNumberOfTablets
and the other one is txtTotalQuantity
.
I have a HiddenField and I am setting its value in code behind file on page load.
hdfMedicationDosage = "2/3/4开发者_Go百科";
What I want is, whatever user enters to txtNumberOfTablets
textbox, should be multiplied with hdfMedicationDosage
value when focus is out of txtNumberOfTablets
.
For example txtNumberOfTablets
contains value 2, and focus is out of txtNumberOfTablets
, then that txtTotalQuantity
will have a value 2*2/3*2/4*2
i.e.4/6/8
I want to achieve this in JavaScript.
You should create a function that takes the string value in hdfMedicationDosage
and uses the string.split() method to get an array of the numbers as strings. Then just iterate through the array and convert each string using Number before doing each multiplication. You can then concatenate the values back together as strings to populate txtTotalQuantity
.
You can see this fiddle for a way to do this.
$(document).ready(function(){
var theValue = "2/3/4", multiplier = '2', newArray=[], valArray;
valArray = theValue.split('/');
for(var i=0;i<valArray.length;i++){
newArray.push(valArray[i] * multiplier);
}
var newValue = newArray.join('/');
$("#result").text(newValue);
});
精彩评论