Using “SELECTINDEX” property in Java Scripts

A college friend of mine asked for support re his Web Development project. He is developing an online banking application using HTML with Java Scripts. His page will be able to add deposits and subtracts withdrawals from the user’s current balance. A form selection (in a form of <SELECT> tag) is used to choose whether the transaction is DEPOSIT or WITHDRAW.

His program should call a Java Script function that would either add or subtract depending on the chosen transaction. Apparently, this is his problem. I realized upon observing his code that the said SELECT tag is only calling one function that only does the same function – subtracting the amount entered to the one existing.

To solve this – the SELECTINDEX property should be used to determine which transaction the user has chosen. Here is a code snippet that I’ve created:

<script language = “JavaScript”>
function doMath()
{
if (document.myform.selection.selectedIndex == 0)
document.myform.text3.value = parseInt(document.myform.text1.value) + parseInt(document.myform.text2.value);
else
document.myform.text3.value = parseInt(document.myform.text1.value) – parseInt(document.myform.text2.value);
}
</script>

Notice that the doMath() function does the following tasks – check whether the option (with an index of 0) is selected. If it is true, the text3 value of the form will be taken from the sum of deposit and existing amount. If false, it will do the subtraction. Actually, the selectIndex property has an integer value that starts with zero (0).

He smiled when I sent this. Problem solved. :D

Take note:
You will notice from the given code snippet that the parseInt() method is used. This is for the purpose of converting the value of text1 and text2 to an integer from its original type of string.

1 Comment(s)

  1. alert(‘wawa’);


Comments RSS TrackBack Identifier URI

Leave a comment