Reputation: 1458
I'm trying to return some text which was inputted into a textbox element on my website. After entering some text into it I noticed that this didn't return data:
document.getElementById('myTextBox').text;
But this did:
document.getElementById('myTextBox').value;
EDIT: The javascript above was used client side to test what was being read, using .text returns an empty string which, when passed back to the server, did indeed show an empty string. .value contained my entered data but when I tried using .value server side the errors occurred.
However in my .cs class when I tried to add the following:
string myInput = myTextBox.Value;
I get an error message saying
"System.Web.UI.WebControls.TextBox doesn't contain a definition for 'Value'...".
The example I was referencing came from here: http://www.aspsnippets.com/Articles/Get-value-of-HTML-Input-TextBox-in-ASPNet-code-behind-using-C-and-VBNet.aspx
My textbox is declared like:
<asp:TextBox ID="myTextBox" runat="server"></asp:TextBox>
However when I try to change the TextBox element to an Input element I get an error saying "The type or namespace name 'Input' does not exist..."
How can I pass the data which was entered into my TextBox back to the server?
Upvotes: 0
Views: 3026
Reputation: 514
To get the text of your textbox for a javascript function :
function GetValueOfmyTextBox()
{
var myTB = document.getElementById('<%= myTextBox.ClientID %>');
alert(myTB.value);
}
Upvotes: 0
Reputation: 5742
HTML elements e.g (input) are not accessible in your code behind. Asp.Net controls like the one you used can be accessed if you use the runat="server" attribute.
If you want to access yout Asp.Net textbox in your codebehind (.cs) you don't need javascript. Just use:
string value = this.myTextBox.Text
But, if you textbox is only a HTML input, than, you need to use some Javascript logic to get the value of the input and pass it to your .cs file.
For that, you have to do something like this: Passing values from javascript to code behind in ASP.NET
Upvotes: 1
Reputation: 21795
In the tutorial you are refering they have demonstared how to access the html input textbox value at server side. You are mixing a html control and a asp.net server control.
This represents a ASP.NET server control:-
<asp:TextBox ID="myTextBox" runat="server"></asp:TextBox>
and you can access its value at server side (.cs file) like this:-
string vaue = myTextBox.Text;
On the other hand the html input
can be converted into a server control by adding the runat="server"
attribute like this:-
<input type="text" id="txtName" name="Name" value="" />
In this case it is HtmlInputText
and you need to access it value like this:-
string value = txtName.Value;
Upvotes: 1
Reputation: 360
Use:
string myInput = myTextBox.Text;
This give you all the text typed in the textbox
Upvotes: 0