Unable to get value of input using ASP.NET - javascript

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?

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;

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

Use:
string myInput = myTextBox.Text;
This give you all the text typed in the textbox

To get the text of your textbox for a javascript function :
function GetValueOfmyTextBox()
{
var myTB = document.getElementById('<%= myTextBox.ClientID %>');
alert(myTB.value);
}

Related

access local storge with javascript and C#, asp.net

i am hoping someone will help me, i am pulling out my hair for the last few hours...!
I am using asp.net web forms with c#
I have the following button in my menu , this button opens up a page that lists selected properties for realtor…
htmlCode.Append("<button type='button' class='btn btn-basic' id='btnEnquire' onclick='openEnquiryPage()'> <span class='glyphicon glyphicon-th-list'></span> View my list </button>");
function openEnquiryPage() {
location.href = "EnquiryPage.aspx";
//get the list from the storage into the hidden field
//getListOfProperties();//not in use...
}
The list is stored in localstorage as Json, I can see the correct data in the text box on the page
var retrievedData = localStorage.getItem("propertyArray");
proplist2.value = retrievedData;
declared as follows in asp.net control
<asp:TextBox ID="TextBox1" runat="server" Text="initial"></asp:TextBox>
BUT in the hidden field, the data is always = ""
<asp:HiddenField ID="txtPropList" runat="server"></asp:HiddenField>
javascript to populate the hidden field...
function getListOfProperties() {
document.getElementById("body_content_txtPropList").value = retrievedData;
var proplist2 = document.getElementById("body_content_txtPropertyList");
proplist2.value = retrievedData;
}
when I debug the following lines in the code behind ...
Page.ClientScript.RegisterStartupScript(this.GetType(),"prop", "getListOfProperties();",true);
_propertyListJson = txtPropList.Value;
propertyListJson I always = “”
Thank-you in advance.!
If you want to use the hidden field then you should use
<%=txtPropList.ClientID%>
as on when you render the page and see it in inspect element server would render the different Id so it would not store the value in hidden field simply so it is feasible to use ClientID to create the static mode. But as on when you call the javascript function from the c# code then it would call the javascript function but it would not wait for it and execute the next line of code as on at that time the value is not store in hidden field so it would return the null value.
If you want then call the function of javascript on page load event and then click the button and retrieve the value it would successfully retrieve the value but i dont think that these would be the feasible code from my opinion
I suggest to create the WebAPI which would simply get the the data from the localstorage and perform the operation
And webAPI can be easily called from javascript using ajax call
I hope this would be helpful and answer is satisfactory 😊☺
Thank You ☺🙂

How to read text box text set by JavaScript from code behind?

I have one ASP.net text box on my page. I am setting text property of this text box using JavaScript. Now, I want to access this text value from back-end (using C#). However, whenever I try to access it, I am getting the old value (the one set up during page load) and I am not able to get the value set by JavaScript code.
Am I missing something here?
ASPX markup of the text box -
<asp:TextBox ID="txtMessage" runat="server"></asp:TextBox>
JavaScript to edit this text box -
var txtMessage = document.getElementById("txtMessage");
txtMessage.Value = "New Value";
C# code to access text box text -
string strMessage = txtMessage.Text; // This does not return value set by above JS function
You just have to change this line in the JavaScript:
txtMessage.value = "New Value"; // the "v" in ".value" needs to be lowercase
UPDATE: I set up an ASP.NET page to make sure that the OP's code did in fact work with that one change, just to make sure I wasn't missing any other little typo. However, as Igor pointed out in his comment, it's a good practice to use the control's ClientID property to account for any prefixes that the .NET runtime might add to an HTML element's id.
So the two lines in your JavaScript should be changed to this (also confirmed to work correctly):
var txtMessage = document.getElementById("<%= txtMessage.ClientID %>");
txtMessage.value = "New Value";
When ASP.Net delivers the page to be render, the name of the controls are changed by prepending a suffix that identifies the container that hold them. From JavaScript, you must ensure to get the correct ID of ASP controls by accessing the .ClientID property.
//gets the element by its ID according to ASP rules
var txtMessage = document.getElementById("<%=txtMessage.ClientID%>");
//the "value" property is lowercase
txtMessage.value = "New Value";

Set Text property of asp:label in Javascript PROPER way

I have a series of textboxes on a form. When the user inserts numbers into these textboxes, calculations are made and <asp:Label> controls are updated via JavaScript to reflect these calculations:
document.getElementById('<%=TotalLoans.ClientID %>').innerHTML = TotalLoans;
This correctly updates the UI. However, when I try to access the value in the codebehind, the Text property is empty. This makes sense I guess, since I was updating the innerHTML property via the JavaScript.
//TotalLoans.Text will always be equal to "" in this scenario
double bTotalLoans = string.IsNullOrEmpty(TotalLoans.Text)
? 0.00
: Convert.ToDouble(TotalLoans.Text);
How do I update the Text property of the <asp:Label> via JavaScript in such a way that I can read the property in the codebehind?
Update
This is a small problem on a large form that contains 41 labels, each of which displays the results of some calculation for the user. Taking the advice of FishBasketGordo I converted my <asp:Label> to a disabled <asp:TextBox>. I'm setting the value of the new textbox as such:
document.getElementById('<%=TotalLoans.ClientID %>').value = TotalLoans;
Again, in the codebehind, the value of TotalLoans.Text is always equal to "".
I don't mind changing how I approach this, but here's the crux of the matter.
I am using JavaScript to manipulate the property values of some controls. I need to be able to access these manipulated values from the code behind when 'Submit' is clicked.
Any advice how I can go about this?
Update 2
Regarding the answer by #James Johnson, I am not able to retrieve the value using .innerText property as suggested. I have EnableViewState set to true on the <asp:Label>. Is there something else I am missing?
I don't understand why, when I type in a textbox and submit the form, I can access the value in the codebehind, but when I programmatically change the text of a textbox or label by way of JavaScript, I cannot access the new value.
Place HiddenField Control in your Form.
<asp:HiddenField ID="hidden" runat="server" />
Create a Property in the Form
protected String LabelProperty
{
get
{
return hidden.Value;
}
set
{
hidden.Value = value;
}
}
Update the Hidden Field value from JavaScript
<script>
function UpdateControl() {
document.getElementById('<%=hidden.ClientID %>').value = '12';
}
</script>
Now you can access the Property directly across the Postback. The Label Control updated value will be Lost across PostBack in case it is being used directly in code behind .
This one Works for me with asp label control.
function changeEmaillbl() {
if (document.getElementById('<%=rbAgency.ClientID%>').checked = true) {
document.getElementById('<%=lblUsername.ClientID%>').innerHTML = 'Accredited No.:';
}
}
Use the following code
<span id="sptext" runat="server"></span>
Java Script
document.getElementById('<%=sptext'%>).innerHTML='change text';
C#
sptext.innerHTML
Instead of using a Label use a text input:
<script type="text/javascript">
onChange = function(ctrl) {
var txt = document.getElementById("<%= txtResult.ClientID %>");
if (txt){
txt.value = ctrl.value;
}
}
</script>
<asp:TextBox ID="txtTest" runat="server" onchange="onChange(this);" />
<!-- pseudo label that will survive postback -->
<input type="text" id="txtResult" runat="server" readonly="readonly" tabindex="-1000" style="border:0px;background-color:transparent;" />
<asp:Button ID="btnTest" runat="server" Text="Test" />
Asp.net codebehind runs on server first and then page is rendered to client (browser). Codebehind has no access to client side (javascript, html) because it lives on server only.
So, either use ajax and sent value of label to code behind. You can use PageMethods , or simply post the page to server where codebehind lives, so codebehind can know the updated value :)
Since you have updated your label client side, you'll need a post-back in order for you're server side code to reflect the changes.
If you do not know how to do this, here is how I've gone about it in the past.
Create a hidden field:
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
Create a button that has both client side and server side functions attached to it. You're client side function will populate your hidden field, and the server side will read it. Be sure you're client side is being called first.
<asp:Button ID="_Submit" runat="server" Text="Submit Button" OnClientClick="TestSubmit();" OnClick="_Submit_Click" />
Javascript Client Side Function:
function TestSubmit() {
try {
var message = "Message to Pass";
document.getElementById('__EVENTTARGET').value = message;
} catch (err) {
alert(err.message);
}
}
C# Server Side Function
protected void _Submit_Click(object sender, EventArgs e)
{
// Hidden Value after postback
string hiddenVal= Request.Form["__EVENTTARGET"];
}
Hope this helps!
The label's information is stored in the ViewState input on postback (keep in mind the server knows nothing of the page outside of the form values posted back, which includes your label's text).. you would have to somehow update that on the client side to know what changed in that label, which I'm guessing would not be worth your time.
I'm not entirely sure what problem you're trying to solve here, but this might give you a few ideas of how to go about it:
You could create a hidden field to go along with your label, and anytime you update your label, you'd update that value as well.. then in the code behind set the Text property of the label to be what was in that hidden field.

Is there a way to grab the first field in a Struts form?

What I want to do is give the first field focus, but since the name is generated dynamically I need a way to set the focus attribute to be the first field. Is there a placeholder like form.field[0] or something like that?
I would set fields styleid and reference it once page is loaded.
JSP:
<html:text styleId="tofocus" property="prop" name="<%=dynamic %>" />
JavaScript
function setFocus()
{
document.getElementById('tofocus').focus();
}
window.onload = setFocus;

Javascript to get sharepoint form field value to a variable

I want to copy the content of a sharepoint form field to a variable using Javascript.
Eg. I have a field named "Language" in my sharepoint edit form. Now I just want to get the value of that field to a varaible x.
Please help.
BR
It depends on the type (e.g. user, lookup, multilookup, text, note, etc.) of field. I am using jQuery in my custom list forms and the name of the field for any given content type will be added to the id of the corresponding html control with the text 'Field' appended to it. However, like any typical asp.net control, the id of the html form control rendered to the client will reflect its control hierarchy so you have to account for that when searching for a field. anyhow, the following works for me if i need to reference fields in my custom forms. ** notice the +Field which implies that the name of the field is concatenated with 'Field'
var $titleField = $('input[id*=TitleField]');
var $lookupField = $('select[id*=Name_Of_Field+Field]')
var $multiLookUpCandidate = $('select[id*=Name_Of_Field+Field][id*=SelectCandidate]')
var $multiLookUpResult = $('select[id*=Name_Of_Field+Field][id*=SelectResult]')
var $note = $('textarea[id*=Name_Of_Field+Field]');
You can pick up on the trend by viewing source and seaching for your contenttype/sitecolumn field name. You will find it in an html form control id. use that information to learn how to reference other field types.
Without posting your code its very difficult to understand what you want to do.... to get a value from a form you can do the following :
HTML
<form id="myform">
<input id="myinput" type="text" value="something" />
</form>
JavaScript:
var myinputval = document.getElementById("myinput").value;
myinputval would be "something" in this example
Demo : http://jsfiddle.net/Qk6FZ/
This might help:
http://depressedpress.com/2012/09/24/obtaining-a-javascript-reference-to-a-sharepoint-field/
Using that function you'd get the reference using something like:
var LanguageFld = getFieldRef("Language");
Once you have the refernece it's easy to get the value:
var CurValue = LanguageFld.value;
Hope this helps!

Categories