correct or efficient way of accessing DOM object in aspx pages
-
29-09-2020 - |
Question
I want to get the value of textbox that a user enters. Below is the code snippet of aspx page :
<asp:TextBox id="txtUserName" runat="server" />
Now which is the best way to access DOM object in aspx page
1.
<script type="text/javascript">
var value= document.getElementById(<%= txtUserName.ClientID %>).value;
alert(value);
</script>
2.
<script type="text/javascript">
var value= document.getElementById("txtUserName").value;
alert(value);
</script>
Solution
SharePoint 2013/SharePoint Online
In .NET Framework 4 was introduced ClientIDMode property that specifies how ASP.NET generates the ClientID
for a control that can be accessed in client script.
To summarize, since SharePoint 2013 targets .NET Framework 4, ClientIDMode
could be utilized that simplifies the access of control in the client side as demonstrated below:
Example:
<asp:TextBox id="boxUserName" runat="server" ClientIDMode="Static" />
JavaScript:
var boxUserName = document.getElementById("boxUserName")
SharePoint 2010 and earlier versions
Prerequisites: jQuery library is used that offers a powerful set of tools for matching a set of elements in a document.
Option 1
Use selector to find element by Id, for example:
var quickLaunch = $('[id$=V4QuickLaunchMenu]'); // find element with id which ends with the text 'V4QuickLaunchMenu'
Option 2
Use CssClass
to specify element class, for example:
<asp:TextBox id="boxUserName" runat="server" CssClass="text-box" />
and then use class selector:
var boxUserName = $('input.text-box');
References
OTHER TIPS
Option 1 is the correct way to do but just change the variable name to something different as it is JavaScript keyword
<script type="text/javascript">
var _value= document.getElementById(<%= txtUserName.ClientID %>).value;
alert(value);
</script>
But I prefer to use jQuery which make life much easier. For that add jQuery file in your aspx or masterpage. Then use below line
<script type="text/javascript">
$(document).ready(function(){
var _value= $(<%= txtUserName.ClientID %>).val();
alert(value);
});
</script>