Can't read value from textbox into javascript variable - c#

Hello I am trying to read a textbox(runatserver) after is gets populated form the server into a javascript variable,but it gives me a console error that "can't read form NULL" however the text box is populated by the string I want to read
this is my text box:
<form runat="server">
<asp:TextBox ID="ServerSideTextBox" runat="server" />
</form>
This is how I am populating it in C#:
ServerSideTextBox.Text= Object_JSON_Class.JSON_DataTable(dt);
it gets the right data also shows the right data string but the PROBLEM is when I try to read the value of the text box like this:
var oServerSideTextBox= document.getElementById("ServerSideTextBox");
var oServerJSON_String=eval("("+oServerSideTextBox.value+")");
I get a console error that I can't read form NULL,but the text box does have the string I want to read into javascript variable,please help

var txtToIncr = document.getElementById('<%=ServerSideTextBox.ClientID%>')
Check out this link, about reading ASP.Net controls through javascript

Try this:
var oServerSideTextBox= document.getElementById("<%=ServerSideTextBox.ClientID%>");
If that does not work, try something like this:
var oServerSideTextBox= document.getElementById("<%=ServerSideTextBox.ClientID%>_text");
Components are assigned different ID's when rendered by the client's browser. You can take a look here for more information.

put this on yout textbox ClientIDMode="Static"

Your server textbox's ID will be different if you use it in a master page structure , try finding its id.Because its actual id might be something like this ctl00_ContentPlaceHolder1_ServerSideTextbox.Check that.
Assign a class to yout textbox then try this to find the id.
$('.textbox').on('blur', function() {
var error = this.id;
alert(error);
)};

Reading the comments. I think you're referring to the wrong textbox-ID..
So I made a small test-thingy: this should work.. If not look into the source from your HTML - there you can see the ID.
<script type='text/javascript'>
function testvalue() {
var oServerSideTextBox = document.getElementById('<%=ServerSideTextBox.ClientID%>');
if (oServerSideTextBox == null) {
alert('this is null');
}
else {
alert(oServerSideTextBox.value);
}
}
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="ServerSideTextBox" runat="server" Text="Testvalue" />
<input type='button' onclick='testvalue();' value='Click' />
</div>
</form>
</body>

Related

asp.net passing values from JS/jquery to code behind c#

I have tried "every" possible way of sending the screen.width vlaue from the JS script on the aspx page to the c# in the code behind and while I can see the screen.width being assigned correctly it never gets assigned to my hidden field value.
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:HiddenField ID="hiddenfield" runat="server" />
<script type="text/javascript" language="javascript">
$(function(){
$('#hiddenfield').val(screen.width);
});
</script>
other content
</asp:Content>
and the code behind:
protected void btnChartGo_Click(object sender, EventArgs e)
{
string s = hiddenfield.Value;
}
No matter what I try s is always ""
Something wrong with the above, everyone seems to be doing it like that and it works?
The ID of the rendered hidden field isn't "hiddenfield" - it'll be something like ctl00_bodycontent_hiddenfield.
Try using
$('[id$="hiddenfield"]')
as the selector instead.
<asp:HiddenField ID="hiddenfield" runat="server" ClientIDMode="Static">
</asp:HiddenField >
Make sure client ID mode of your hidden field is static if you are using ASP.NET 4 or use
$('#<%= hiddenfield.ClientID %>').val(screen.width);
This should get the right selector:
$('#<%= hiddenfield.ClientID %>').val(screen.width);
Check the view source of the page and find out proper id of the element and then use jquery selector over it and then at the page load check for request.form collection to check if hidden variable is coming in post request or not

ASP.NET and C# FileUpload

I have a asp file upload for pictures and what I want to do is, when the file chosen has the same name as the previous file it should pop something up that says "This image name already exists, do you want to replace it? if yes then it would just override the current picture with the new one but if not then just leave it alone. How can I do this?. Right now I have this. Also if the solution is in javascript I could also use that (but i am not too good with javascript :) ) Thank you
<div class="style">
Choose an Image: <asp:FileUpload ID="getImage" runat="server" Width="150px" BorderStyle="Inset" EnableViewState="true" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator"
runat="server" ControlToValidate="getImage" CssClass="Error" Display="dynamic" ValidationExpression=".*(\.[Jj][Pp][Gg]|\.[Gg][Ii][Ff]|\.[Jj][Pp][Ee][Gg]|\.[Pp][Nn][Gg])" ErrorMessage="Select a correct file format"></asp:RegularExpressionValidator>
</div>
Please be aware I am a total newbie with Javascript so if that is what's going to work please explain as if I was a 5 year old.
I really appreciate the help.
My solution will perform the check just before postback. I also use jquery a little bit.
The important piece of the puzzle here is retrieving the previous file name. I created a PageMethod to do this part. So in my aspx.cs file I have a function that looks like this:
using System.Web.Services;
.......
[WebMethod()]
public static string GetPreviousFileName()
{
//put logic here to get the filename to compare against.
return "somefilename.ext";
}
You'll need to implement your own logic for how to retrieve the file name. Another, simpler but less flexible, approach for handling the previous file name would be to add an asp:hiddenfield to your page and populate it with the name of the previous file on page load. Then you could compare by reading $('#<%= hiddenField.ClientID %>').val().
Next I used the following code for my file upload control and a submit buton:
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true" />
<div>
<asp:FileUpload ID="fu" runat="server" />
<asp:Button ID="btnUpload" runat="server" OnClientClick="return checkDuplicateFile();" Text="Upload File" />
</div>
Two important things to note here: The ScriptManager has EnablePageMethods="true" and the asp:button has an OnClientClick attribute specified. Lastly, the javascript part of the solution which retrieves the value from the page method and and compares the file names:
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var oFilename = "";
$(function () {
//get original file name on page load
PageMethods.GetPreviousFileName(function (result) {
oFilename = result;
});
});
function checkDuplicateFile() {
var newVal = $('#<%=fu.ClientID %>').val();
var newValFile = newVal.substr(newVal.lastIndexOf("\\") + 1);
//returning true causes postback, returning false stops postback.
if (newValFile == oFilename) { return confirm("This image name already exists, do you want to replace it?"); }
else return true;
}
</script>
Couple of things going on here. We use our pagemethod to pull in our old filename from the page method on page load (PageMethods.GetPreviousFileName). Next we setup the function which will be called by our buttons onClick event (client side). The <%=fu.ClientID %> snippet of code will output the client side id of the file upload control for use in our javascript. I do a substring on the file path and extract the file name by pulling back only the text after the last '\' and do the compare.
As my comment in the function says, returning true/false from a function called in the OnClientclick event determines whether a post back occurs. So if the user clicks yes in the confirmation box then a postback occurs, else if they click no then none occurs.
Hope that at least gets you going in the right direction.
Add the code below to your submit button
OnClientClick="return confirm('Are you sure you want to delete this file?')"
Edit as someone pointed out this will ask this question without taking in concern previous file and new one. It will do basic job.
My question is whether you doing this for edit mode or in new item mode. I mean are you editing item or adding new one on page you are interested to check?

How do I get label value as a parameter into a javascript function?

Hopefully this one is not too hard to understand but I just want the label values to be inputs into a javascript function. Might be better to explain with code:
ASP.NET Label code:
<asp:Label ID="LabelCL" runat="server" Text="A single int filled in by DB"></asp:Label>
Page Source:
<span id="ctl00_cpMainContent_LabelCL">7</span>
What I would like to achieve but am not sure how to do:
<span id="ctl00_cpMainContent_LabelCL"> <script type="text/javascript">functionX(7)</script> </span>
So basically just wrap the output int in the following:
<script type="text/javascript">functionX( VALUE FROM LABEL TEXT)</script>
within the
<span></span>
Try this
<asp:Label ID="LabelCL" runat="server" />
<script type="text/javascript">
var value = document.getElementById("<%= LabelCL.ClientID %>").innerHTML;
functionX(value);
</script>
If it is called just after render you can simply use LabelCL.Text, if you need the value after and if it can be edited you can do as the exemple above.
With jQuery you can use
$("[id$=LabelCL]")
to retrieve the element.
var span = document.getElementById('ctl00_cpMainContent_LabelCL'),
text = span.firstChild;
functionX(text.textContent);
Working Demo
or if defined in the Page use script tags to render out the client id for the span using
<%= LabelCL.ClientID %>
Try this:
<asp:Label ID="LabelCL" runat="server" Text="A single int"></asp:Label>
<button onclick="displayContent(<%= LabelCL.ClientID %>)">click me</button>
<script>
function displayContent(obj) {
alert(obj.innerText);
}
</script>
You almost had it:
<asp:Label runat="server" Text="<script type='text/javascript'>document.write(functionX(7));</script>"/>
Use this piece of code
onclick="myFunction(labelName.innerText)"

ASP.NET How to read HTML Form Element?

I have an ASP.NET web form where I have an hidden field, like this:
<form id="form1" runat="server" action="http://localhost/fa/Default.aspx">
<div>
<input id="requestData" type="hidden" name="requestData" value="" runat="server" />
<asp:Button ID="btnPOST" Text="POST" runat="server" OnClick="do_POST" />
</div>
</form>
On the method do_POST I have this:
protected void do_POST(object sender, EventArgs e)
{
//requestDataField is of the type protected global::System.Web.UI.HtmlControls.HtmlInputHidden requestData;
requestDataField.Text = "FOO!";
}
When I submit the form (by pressing the button), it goes to the server (an handler) wheer I have this:
string requestData = context.Request.Form["requestData"];
I get an empty string..
But if I assign a value like this:
<input id="requestData" type="hidden" name="requestData" value="FOO" runat="server" />
I get the "FOO"
What am I missing?
The reason why it's not doing it is because the method is called after the page has been post back. Meaning, it is actually working if you change .Text to .Value unfortunately by that time you have already read your form and it was an empty value. I remember working on a project where you could tell your form not to submit until a function has been run (but it was with a javascript that needed to run an complete before aspx submitted). You should try to see if there is a way to force your form to run your function BEFORE doing the postback.
Your do_POST method runs on the server, not on the client, and so is setting the value of the server-side object which represents the <input> control. Your context.Request.Form["requestData"] gets the value of the field from the client side data submitted in the POST request, which was never set, so it is blank.
If you want the onClick to be a client-side function, then you need to do it a little differently. Use the OnClientClick attribute (instead of onClick). Then create a javascript method to set the field value:
<asp:Button ID="btnPOST" Text="POST" runat="server" OnClientClick="do_POST" />
<script>
function do_POST() {
document.getElementById("requestData").value = "FOO!";
}
</script>
I tried your code and did few changes to it.
Change requestDataField.Text = "FOO!"; to requestData.Value = "FOO";
Also I added two buttons. One for do_POST function and the UseSubmitBehaviour property is set as False. The other one was to submit the form.
If you want to set it on client side then you will have to use Javascript.
Use "Value" instead of "Text" property for HtmlInputHidden control:
requestDataField.Value = "FOO!";
instead of
requestDataField.Text = "FOO!";

Get clientid in user control from external javascript file

I am developing a user control (ascx) in ASP.NET which uses javascript for manipulating controls. Currently the javascript code is inlined and uses <%= somecontrol.ClientID %> to get the control it needs.
I want to put the javascript file in external file but from external file I cannot use the above syntax for retrieving controls. I have read about possible solutions in this and this answers but the problem is that the user control can be placed multiple times on page. This means that the Controls array (mentioned in the answers) will be rendered several times with different items. As a result the script will not be able to retrieve the id it needs. If I put <%= ClientId %> in the name of array that holds items then I will have the same problem as I am trying to solve.
Any ideas?
Ok, a different approach, that I try to use a JavaScript-class style, and then initialize it for each control.
In the external javascript file, write your code as:
function oNameCls(ControlId1) {
this.ControlId1 = ControlId1;
this.DoYourWork1 = function() {
// use the control id.
// this.ControlId1
}
this.DoYourWork2 = function() {
// use the control id.
// this.ControlId1
}
}
And on the control do the call like that.
<script language="Javascript" type="text/javascript">
// init - create
var <%=this.ClientID%>MyCls = new oNameCls(<%=Control1.ClientID%>);
// do your work
<%=this.ClientID%>MyCls.DoYourWork1();
</script>
Hope now help better.
The way I solve this problem is to use CSS classes or place the controls within containers with known IDs and then traverse into the container's children to get the actual controls. For example:
<asp:TextBox ID="Something" runat="server" CssClass="mycontrol" ... />
Could be accessed via:
jQuery('.mycontrol');
Or:
<div id="ControlContainer">
<asp:TextBox ID="Something" runat="server" ... />
</div>
Could be accessed via:
jQuery("#ControlContainer input[type='text']");
The only real problem with this approach is you're tying your code to specific markup on the page, which can be a hassle if the markup changes a lot.
What about a hidden variable:
<input type="hidden" id="ClientId" value="<%=ClientId %>">
Then from your js:
$("#" + $("#ClientID").val())
Or, put the hash in:
<input type="hidden" id="ClientId" value="#<%=ClientId %>">
...
$($("#ClientID").val())
If you want to find a specific control when there could be multiple copies, this can't be done. How would the external javascript know which of the n controls you wanted?
How can rig the behavior up to a class and find the elements relative to the position of the action control, like this:
UserControl:
<div class="myControl">
<asp:Button id="MyButton" runat="server" Text="Click Me" />
<div style="display:none;">Show me!</div>
</div>
If you jQuery was written to be relative like this:
$(".myControl input").click(function() {
$(this).next().slideDown();
});
In this case, it doesn't matter what the specific IDs are, as long as you can navigate the DOM relatively to the controls you need. Even if it's more complex like .closest("div").next().find(".bob").prev()...whatever you need to get there works.

Categories