codebrain
codebrain

Reputation: 13

How to use a common fuction for all the buttons in VBScript?

The functions I am using are:

sub sin_onclick()
Dim a,b,r
a=document.f.field.value
b=document.f.sin.value
r=a+b
document.f.field.value=r
end sub

sub cos_onclick()
Dim a,b,r
a=document.f.field.value
b=document.f.cos.value
r=a+b
document.f.field.value=r
end sub

sub clear_onclick()
Dim a,b,r
r=""
document.f.field.value=r
end sub

In the html I am having the following buttons:

<input type="button" name="clear" value="clear" />
<input type="button" name="cos" value="cos" >
<input type="button" name="sin" value="sin" >

What I am doing actually is a scientific calculator. If am using a function for a means a lot of code. So I need a common function which runs when all the buttons are called and get the value of the called button. Is it possible? if yes how?

Upvotes: 1

Views: 132

Answers (1)

Kul-Tigin
Kul-Tigin

Reputation: 16950

You can attach a general subroutine to the onclick events of your buttons like this:

Sub GeneralButton_Click()
    Dim sender
    Set sender = window.event.srcElement

    'Common Operations

    MsgBox "A button clicked"

    'Dim a,b,r
    'a=document.f.field.value
    'b=document.f.sin.value
    'r=a+b
    'document.f.field.value=r

    'Isolated operations by element name

    Select Case sender.Name
        Case "clear"
            MsgBox "It was 'clear'!"
        Case "cos"
            MsgBox "It was 'cos'!"
        Case "sin"
            MsgBox "It was 'sin'!"
    End Select
End Sub

Sub Window_OnLoad
    Dim Elm
    For Each Elm In Document.getElementsByTagName("input")
        If Elm.Type = "button" Then
            Elm.Onclick = GetRef("GeneralButton_Click")
        End If
    Next
End Sub

Upvotes: 2

Related Questions