Accessing hidden field value in javascript - javascript

I have a hidden field in my form, I'm setting the hidden field's value on the server and trying to access this value from javascript,
I get the error: Unable to get value of the property 'value': object is null or undefined
If I view the source the hidden field value is set and the ID of the hidden field is the same as the ID I'm calling.
ASPX
var v = document.getElementById('hxValue').value;
<asp:HiddenField ID="hxValue" runat="server"/>
VB
hxValue.Value = "Value1"
I recall doing this before and it should be relatively simple but for some reason, i'm not getting it right.

Your code will work. For simple forms, just add
<asp:HiddenField ClientIDMode="static" ID="hxValue" runat="server"/>
OR
you need to find the client id using
'<%=hxValue.ClientID%>'

Ok it appears my hidden field's value had not been set before the script had run, therefore receiving a null value. I had assumed that placing breakpoints on the server page load and the script would establish if the control was being set before the script ran, appears not.
Fixed as below:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script type="text/javascript">
function GetHiddenValues() {
var v = document.getElementById('<%= hxValue.ClientID %>').value;
}
</script>
</head>
<body onload="GetHiddenValues() ;">
<form runat="server">
<asp:HiddenField ClientIDMode="static" ID="hxValue" runat="server"/>
</form>
</body>
</html>
Thanks for all the assistance.

You can use innerText not value to retrieve the value of hxValue.
var v = document.getElementById('hxValue').innerText
If you were using jQuery you could also do
var v = $("#hxValue").val();

Try this
var v = document.getElementById('<%= hxValue.ClientID %>').value;
Problem is that Hidden Field is server side control and it's ID that you have given is a server side ID, you will have to get client side ID of that control to refer it in your client side JavaScript or Jquery.
Update
put this script at the end of your page, just before </body> something like this
<script type="text/javascript" language="javascript">
var v = document.getElementById('<%= hxValue.ClientID %>').value;
</script>
</body>

Try <asp:HiddenField ID="hxValue" runat="server" Value=""/>
Then call it by id and set value

Related

how to pass javascript variable to server side asp.net

I am trying to write javascript variable(hdnField) to server side. In javascript code I have assigned the value of "HiddenField" Control and then I want to write this value to server side. Here's my Client side script:
<script type="text/javascript">
var hdnField = document.getElementById('<%= hdnField.ClientID%>');
hdnField.value = 100;
</script>
Server side:
<form action="#" runat="server">
<div class="left"><%Response.Write(hdnField.Value);%></div>
<asp:hiddenfield id="hdnField" runat="server" ></asp:hiddenfield>
</form>
I viewed the Page src and was able to retrieve the "hdnField" which is :
<input id="hdnField" type="hidden" name="hdnField" value="100 ">
I don't know where
<div class="left"><%Response.Write(hdnField.Value);%></div>
Comes into play because that looks more ASP than ASP.NET web forms, but if you have:
<asp:hiddenfield id="hdnField" runat="server" ></asp:hiddenfield>
You can read and write to this on the client via:
document.getElementById('<%= hdnField.ClientID %>').value = 'XYZ';
alert(document.getElementById('<%= hdnField.ClientID %>').value);
On the server, you can read and write to this via:
hdnField.Text = "XYZ";
var text = hdnField.Text;
As long as hdnField is not in a template or list control, you can refer to it directly on the server, with the <asp:HiddenField> control you can do both. This bridges the gap so that you can change the value on the client, then retrieve the value on postback. AJAX is only necessary if you need to send the value to the server before the next postback occurs, or out of the normal flow of the ASP.NET postback lifecycle.

Accessing value of hidden variable in Javascript wiht VB

I tried the following code but did not succeed.It would be great if you could guide me. I was trying to test using a simple "Hello". In the actual program I would assign a string value to the hidden field.
I get an Alert box ( using this to test whether the value is accessible in javascript ) but with no values.
Server Side
ivar.Value = "Hello"
Javascript
<script>
function getval() {
var v = document.getElementById('<%= ivar.ClientID%>').value;
alert(v)
}
</script>
Form
<asp:Button ID="Button1" runat="server" Text="CALCULATE" onclientclick="getval()" />
<asp:HiddenField ClientIDMode="static" id="ivar" runat="server" Value=""/>
Let us say you have a public variable on server side:
public string iVar = "Hello";
You can directly add it to your javascript as below:
<script>
function getval() {
var v = <%=iVar%>;
alert(v);
}
</script>
Hope this helps.
Your call to find the client id in your script block may be trying to find the hidden field before it exists. try moving the script to the bottom of the page just before you close your body tag and see if that helps.

Extracting user entry from text box and storing it in a variable in javascript

// text Box
<asp:TextBox ID="TextBox3" runat="server" BackColor="Silver"
BorderColor="Silver" ontextchanged="TextBox3_TextChanged"
style="margin-left: 6px" Width="154px"></asp:TextBox>
// Submit button
<asp:Button ID="Button6" runat="server" BackColor="Silver"
onClientclick='store_memID()' style="margin-left: 20px" Text="Submit"
Width="102px" Font-Bold="True" Height="28px" />
<script type = "text/javascript">
// Function to caputure client-input- Member_ID.
function store_memID() {
var mem_ID = document.getElementById('TextBox3').value;
return confirm('TimeLine is displayed for: ' + mem_ID);
}
</script>
When I run the code and enter a value into the text box and then press the submit button:-
"Microsoft JScript runtime error: Unable to get value of the property 'value': object is null or undefined".
Else, if I remove the '.value' :-
<script type = "text/javascript">
// Function to caputure client-input- Member_ID.
function store_memID() {
var mem_ID = document.getElementById('TextBox3');
return confirm('TimeLine is displayed for: ' + mem_ID);
}
</script>
and then run the program, enter value in text box and press submit then i get :-
"TimeLine is displayed for: Null"
I have been looking into solving this problem. not sure whats going wrong...
Edit (fix):- Server Side ID for my text box is 'TextBox3' but this doesn't necessarily match up with the client side ID.
to get Client Side ID:- '<%=TextBox3.ClientID%>'
It's been a while since I wrote asp forms but it is likely that the id on the client side (in your browser) is not what you think it is. This is/was one of the major pitfalls of web forms in my mind (This may have been made simpler in version 4.0, you'll have to check that). You could use a css class (and use jQuery or similar to find your element) or inject the client side id into the java script e.g.;
<script type = "text/javascript">
// Function to caputure client-input- Member_ID.
function store_memID() {
var mem_ID = document.getElementById('<%=TextBox3.ClientID%>').value;
return confirm('TimeLine is displayed for: ' + mem_ID);
}
</script>
UPDATE: fixed case error in ClientID as pointed out in comments
You are using asp Text Boxes which are mostly used for server side code. The ID you place in the tag is not guaranteed to match the ID of the element rendered.
You will need to inspect your html in the browser to find the rendered ids. (Likely will look something like: ct100_TextBox3) and use that instead. Or, if you are not doing any server side coding, it would probably be best to convert your text boxes to <input /> fields, or <textarea />.

jQuery file upload refreshing page

I saw this question, "Show Open Dialog on a Button click":
'I have to show a Open Dialog box on a button click. Basically I have to upload a file, for this I am using FileUpload control, but I don’t want to show it to user instead I want to show a Button'
And the answer was :
<script type="text/javascript">
$(document).ready(function() {
$("#btn").click(function() {
$("#FileUpload1").click();
return false;
});
});
</script>
<style type="text/css">
.Class { visibility:hidden;}
</style> </head> <body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btn" runat="server" Text="Send File"/>
<asp:FileUpload ID="FileUpload1" CssClass="Class" runat="server" />
But i tried it and all it does is refreshing the page, anyone know what the problem is?
Because "FileUpload1" is not the ClientID. Just look at the generated HTML source of your page and you will see that.
You should use something like :
<script type="text/javascript">
$(document).ready(function() {
$("#<%= btn.ClientID %>").click(function() {
$("#<%= FileUpload1.ClientID %>").click();
return false;
});
});
</script>
That sounds like a security risk, and I wouldn't be surprised if security prevented that from working.
Take a look at this jQuery Ajax Upload plugin.
I would suggest you to not go that route. If you want to avoid showing FileUpload control to user.. use this.
make the client mode static to be able to access you controls like this
<asp:FileUpload ID="FileUpload1" ClientIDMode="Static" CssClass="Class" runat="server" />
<asp:Button ID="btn" ClientIDMode="Static" runat="server" Text="Send File"/>
All server-side controls (those with runat="server" attributes) have their IDs re-written by ASP.NET. Your IDs will actually look something like ctl00_MainContent_btn.
You can get around this by using <%= btn.ClientID %> server tags or by assigning a CSS class to your controls and referencing that class in JavaScript/jQuery.
Edit: You probably also need to make sure that your ASP button is not a submit button, which would cause the generated page to submit the form.
Your page refreshes because the target of your form is implicitly the current page. You need to set the target of your form to be (for example) a hidden iframe:
<form id="my-form" action="url" target="form-target" method="post">
<!-- your form here -->
</form>
<iframe id="form-target" name="form-target" style="display:none;"></iframe>
<script>
// Assuming you are using jquery
var form = $('#my-form'),
iframe = $('#form-target');
// create a function to be called each time the iframe loads
iframe.load(function () {
var responseText, iframeBody;
// Get the response from the server. It will be in the body tag of your iframe
iframeBody = $(this).contents().find('body');
responseText = iframeBody.text().trim();
// Don't continue until we actually have a response
if (!responseText) return;
// Clear the iframe's html so this function won't be called again for the same content
iframeBody.html('');
// do whatever you want with the response, for example JSON decode it
response = JSON.parse(responseText);
});
</script>

Value set using JavaScript is not persisted on Postback

I have two list controls in my asp.net page and am populating the second list control using javascript. Problem is the script executes and i can see the value moved from first list box (ConfiguredOrgListBox) to second list box(SelectedOrgListBox) but when i try to save using submit button i find my second list as empty and first list box as it was earlier. Below is the script and mark up.
//call this method to register the script
private void CreateMoveOrganizationScript(StringBuilder sb) {
sb.Append( #"<script language=javascript type=text/javascript>;
function moveOrganisation() {");
sb.Append( #"var source = document.getElementById('"+ ConfiguredOrgListBox.ClientID +#"');
var target = document.getElementById('"+SelectedOrgListBox.ClientID+ #"');
if ((source != null) && (target != null)) {
var newOption = new Option();
newOption.text = source.options[source.options.selectedIndex].text;
newOption.value = source.options[source.options.selectedIndex].value;
target.options[target.length] = newOption;
source.remove(source.options.selectedIndex) ;
}
} </script>");
}
Markup
<asp:Label ID="ConfiguredOrgLabel" runat="server" Text="Available Organizations"></asp:Label><br />
<asp:ListBox ID="ConfiguredOrgListBox" runat="server" Width="98%" Height="100px"></asp:ListBox>
<input id="MoveOrgRight" type="button" value=">>" onclick="moveOrganisation()" />
<asp:Label ID="SelectedOrgLabel" runat="server" Text="Selected VNA Organizations"></asp:Label><br />
<asp:ListBox ID="SelectedOrgListBox" runat="server" Width="98%" Height="100px"></asp:ListBox>
Please let me know what I am doing wrong
Regards,
JeeZ
According to this, it's because the list box doesn't post back to tell the back-end that it's changed. They use a hidden field which holds info on what changes were made with JavaScript and then on postback it updates the back-end.
You need to process these changes during postback. When postback happens ASP.NET engine loads control's data from view state and it doesn't know that client modified values using javascript, so you should manually extract those values from Request.

Categories

Resources