Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Textbox value in Javascript

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???

like image 613
Shijilal Avatar asked Feb 18 '11 09:02

Shijilal


People also ask

Which method is used to get the textBox value in JS?

The jQuery val() method is to get the form element's value. Here, the form element means the input , textarea , and select elements.


3 Answers

Use

document.getElementById('<%= txt_model_code.ClientID %>')

instead of

document.getElementById('txt_model_code')`

Also you can use onClientClick instead of onClick.

like image 186
Nirmal Avatar answered Oct 09 '22 10:10

Nirmal


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

like image 36
Sean Taylor Avatar answered Oct 09 '22 12:10

Sean Taylor


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

like image 4
Muhammad Akhtar Avatar answered Oct 09 '22 12:10

Muhammad Akhtar