VS.NET - ASP.NET -Javascript Functions for Textboxes
Synopsis:
There are times when you need to perform some actions on controls without postbacks or that are not possible to perform on the serverside. Here are a handful of examples using Textboxes as an example control.
Solution:
This function can be used to set the text of a textbox control or any other control with a value property. This will not work on a label control because the underlying code is rendered as a span object, if you modify the code to check for control type, you could changethe .value to a .innerhtml as needed.
Public Function SetText(ByVal FocusControl As Control, _
ByVal strText As String, Optional ByVal incTags As Boolean = False) As String
Dim Script As New System.Text.StringBuilder
Dim ClientID As String = FocusControl.ClientID
With Script
If incTags Then
.Append("<script language='javascript'>")
End If
.Append("document.getElementById('")
.Append(ClientID)
.Append("').value = '" & strText & "'; ")
If incTags Then
.Append("</script>")
End If
End With
Return Script.ToString
End Function
Examples of use:
Label2.Attributes.Add("onclick", SetText(TextBox1, "Set on a click event"))
Me.RegisterStartupScript("setText", SetText(TextBox1, "Startup script", True))
The SelectText function selects all the text in the passed textbox control.
Public Function SelectText(ByVal FocusControl As Control, _
Optional ByVal incTags As Boolean = False) As String
Dim Script As New System.Text.StringBuilder
Dim ClientID As String = FocusControl.ClientID
With Script
If incTags Then
.Append("<script language='javascript'>")
End If
.Append("document.getElementById('")
.Append(ClientID)
.Append("').select(); ")
If incTags Then
.Append("</script>")
End If
End With
Return Script.ToString
End Function
Examples of use:
Label1.Attributes.Add("onclick", SelectText(TextBox1))
Me.RegisterStartupScript("selectText", SelectText(TextBox1, True))
The SetFocus function can be used to set the focus to any control which can receive focus
Public Function SetFocus(ByVal FocusControl As Control, _
Optional ByVal incTags As Boolean = False) As String
Dim Script As New System.Text.StringBuilder
Dim ClientID As String = FocusControl.ClientID
With Script
If incTags Then
.Append("<script language='javascript'>")
End If
.Append("document.getElementById('")
.Append(ClientID)
.Append("').focus();")
If incTags Then
.Append("</script>")
End If
End With
Return Script.ToString
End Function
Examples of use:
Label1.Attributes.Add("onclick", SetFocus(TextBox1))
Me.RegisterStartupScript("setFocus", SetFocus(TextBox1, True))