I am trying to get the value of the textbox in a javascript, but its not working. Given below is the code of my test page
<%@ Page Title="" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="false"
CodeFile="test3.aspx.vb" Inherits="test3" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="Server">
<script language="javascript">
function GetAlert() {
var TestVar = document.getElementById('txt_model_code').value;
alert(TestVar);
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
<asp:TextBox ID="txt_model_code" runat="server" ></asp:TextBox><br /><br />
<input type="button" value="db Function" onclick="GetAlert()" /><br />
</asp:Content>
So where am i going wrong?? How to get the text entered in the textbox in the javascript???
The jQuery val() method is to get the form element's value. Here, the form element means the input , textarea , and select elements.
Use
document.getElementById('<%= txt_model_code.ClientID %>')
instead of
document.getElementById('txt_model_code')`
Also you can use onClientClick
instead of onClick
.
This is because ASP.NET it changing the Id of your textbox, if you run your page, and do a view source, you will see the text box id is something like
ctl00_ContentColumn_txt_model_code
There are a few ways round this:
Use the actual control name:
var TestVar = document.getElementById('ctl00_ContentColumn_txt_model_code').value;
use the ClientID property within ASP script tags
document.getElementById('<%= txt_model_code.ClientID %>').value;
Or if you are running .NET 4 you can use the new ClientIdMode property, see this link for more details.
http://weblogs.asp.net/scottgu/archive/2010/03/30/cleaner-html-markup-with-asp-net-4-web-forms-client-ids-vs-2010-and-net-4-0-series.aspx1
Since you have master page and your control is in content place holder, Your control id will be generated different in client side. you need to do like...
var TestVar = document.getElementById('<%= txt_model_code.ClientID %>').value;
Javascript runs on client side and to get value you have to provide client id of your control
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With