PDA

View Full Version : Calculation: Add become append ???


ngaisteve1
02-03-2003, 05:34 AM
How come my javascript can't add but append? Eg, if two var is a and b. a = 100 and b = 200. when I add a to b, it become 100200 instead of 300? What is strange is it can multiply, divide and minus but not add. My code is below. Any idea?

<script language="javascript" type="text/javascript">
function btnCalSource_onclick()
{
tmp_tSource = document.myform.t_source_fr.value;
tmp_mydebt = document.myform.mydebt_fr.value;
tmp_job = document.myform.job_fr.value;

if (tmp_job == "1200")
{
tmp_tSource = tmp_mydebt + tmp_job;
}
document.myform.t_source_fr.value = tmp_tSource;
}
</script>

ngaisteve1
02-03-2003, 07:59 AM
Even though I use ASP also the same result.

<%tmpTSource = request.querystring("mydebt_fr") + request.querystring("job_fr")
response.write tmpTSource%>

kdjoergensen
02-03-2003, 09:23 AM
When you read data from an input element into a variable, the dataform will be 'text'. Since you can append text with an addition sign (+) this explains why your data is being appended instead of subjected to the proper math.

You can use the object Number to convert string data into numbers.

example:
<script language="javascript" type="text/javascript">
function btnCalSource_onclick()
{
tmp_tSource = Number(document.myform.t_source_fr.value);
tmp_mydebt = Number(document.myform.mydebt_fr.value);
tmp_job = Number(document.myform.job_fr.value);



// ERROR HANDLING:

if (!tmp_tSource) {
throwAlert('tmp_tSource');
}
if (!tmp_mydebt) {
throwAlert('tmp_mydebt');
}
if (!tmp_job){
throwAlert('tmp_job');
}

function throwAlert(elmName){
alert("You entered an invalid number. Please re-enter");
document.myform.elements[elmName].focus();
return false;
}




if (tmp_job == "1200")
{
tmp_tSource = tmp_mydebt + tmp_job;
}
document.myform.t_source_fr.value = tmp_tSource;
}
</script>