Hiding/Showing an html table with C# and Javascript - javascript

I am working on website using ajax and C#. I started learning these languages a couple months ago, so I'm not always sure what the best practice is to accomplish things.
I have a form in which certain controls need to be hidden or shown depending on the user's action. It starts out showing an "id" field (along with other fields), but if the user doesn't know their id, they click a link which causes the "id" field to become hidden and displays a table that contains additional controls and a "find" button. I am currently using Javascript to handle the click and hide/display the controls:
function showSearchTable() {
document.getElementById('IDNumberRow').style.display = 'none';
document.getElementById('DontKnowId').style.display = 'none';
document.getElementById('infoSearchTable').style.display = 'block';
}
When the "find" button is clicked, the application attempts to look up the additional info in the database and tells the user the result. As a result of the server call, the page is re-loaded, which causes the table to become hidden again. Here's my problem: if the phone number cannot be found, I would like to keep the table visible so that the user can correct any mistakes.
I have tried adding code that makes the table hidden to the code-behind so that the post-back won't cause the table to become invisible:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
infoSearchTable.Visible = false;
}
}
However, as the table now contains the attribute runat="server" in order to see it in the c# code, I can't seem to reference it in my javascript code in order to set it visible from the client. I tried this for the javascript:
function showSearchTable() {
document.getElementById('IDNumberRow').style.display = 'none';
document.getElementById('DontKnowId').style.display = 'none';
var infoSearch = document.getElementById('<%=infoSearchTable.ClientID%>');
infoSearch.style.display = 'block';
}
and the table's html:
<table id="infoSearchTable" runat="server">
....table rows/columns containing controls
</table>
but I get an error saying that 'infoSearch' is null.
I think I'd be able to accomplish both tasks (set hidden table visible with Javascript, but keep it visible on post back) myself, but I think that my code would end up being more complicated than necessary, especially as I'm new to ajax, .net and C#. So I'm looking for advice - Am I on the right track? Did I use something the wrong way? Is there another way to do this?

if(!Page.IsPostBack)
{
infoSearchTable.Visible = false;
}
I think this will stop the control being sent back to the client (hence the null reference) - try something like:
if(!Page.IsPostBack)
{
infoSearchTable.Attributes.Add("style", "display: none;");
}

You can do something like that
<table id="infoSearchTable" runat="server">
....table rows/columns containing controls
</table>
and in the code behind
infoSearchTable.Attributes.Add("class", "yourclass");
in youe .css
.yourclass{display:none;}

Once you add runat="server" to an element, you have to reference it by the ClientID in JavaScript:
var table = document.getElementById("<%=infoSearchTable.ClientID%>");
if (table){
table.style.display = "none";
}

In ASP.NET when you use runat=server it takes your ID and modifies it to include other information from your program, I forget exactly what but I think the master page or namespace or something to make it unique. Your getElementByID() need to be changed to include all that other information (view source on a page to get the actual ID) or use a javascript framework like JQuery that has advanced selectors for finding elements on a page.

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 ☺🙂

Using telerik radgrid itemcommand with a radwindow to get initial data for InsertMode Dropdowns

I need some assistance with the telerik radgrid's itemcommand to get some information from a user adding a new record prior to opening the Grid in Insert mode. I have the itemcommand working to open a radwindow, present the user with a dropdown list of items to select from and a radbutton to select the value and close the radwindow, then this value is passed back to the parent page in javascript. All the values are passed down and I can use the alert function to validate this.
So at this point I need to continue the flow to open the radgrid in insert mode and filter a dropdown in the insertmode using the value from the radwindow noted above. In order to use this value I'm attempting to assign it to a hidden radtextbox for use in the ItemDatabound event when the form is loading in insert mode. Unfortunately, the value isn't being set via the javascript in this hidden control and is acting like it is erroring somewhere in the javascript. I feel like I'm overcomplicating this but was hoping for some guidance on what others have done to implement something like this.
<asp:LinkButton ID="addNewRecord" runat="server" Text="Add New Record" OnClientClick="openWin(); return false;" OnClick="InitInsert">Add New Record</asp:LinkButton>
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script type="text/javascript">
//<![CDATA[
function openWin(sender, args) {
var oWnd = radopen("ParserFileNewDialog.aspx", "RadWindow1");
}
function OnClientClose(oWnd, args) {
//get the transferred arguments
var arg = args.get_argument();
if (arg) {
var lenderid = arg.LenderID;
var tb = null;
tb = $find("<%=newLenderID2.ClientID %>");
alert(tb.get_text());
tb.set_text(lenderid);
$find("<%=hdnInsertBtn2.ClientID %>").click();
}
}
//]]>
</script>
</telerik:RadCodeBlock>
Any help is greatly appreciated!
What type of control is the newLenderID2 that you attempt to set a value to? With this syntax, it should be a RadTextBox. If it is an asp:HiddenFiel, you need
$get("<%=newLenderID2.ClientID %>").value = lenderid;
If you get an error - what is the error?
Also, you can fire a grid command and pass an argument to it (depending on the command) directly via the grid's masterTableView client-side API and the fireCommand() method: http://www.telerik.com/help/aspnet-ajax/grid-gridtableview-firecommand.html. Thus, you may not need the hidden button at all. A hidden field will suffice for data transmission.

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.

How can i get hidden control id in parent page in the user control page using javascript

How can i get hidden control id in parent page in the user control page using javascript. there is a hidden input control in the page. i want to assign value to this control in the user control page which is used in this page. its an ascx page control.
<input type="hidden" runat="server" name="isChanged" id="isChanged" value="0" />
You could do this using jquery using the 'ends with' selector.
var element = $("input[id$=isChanged]")[0];
This assumes you only have one input on your page with an id which ends in 'isChanged'. The reason we use ends with is because asp will make the client side id of your control something like ct100$placeholder1$mypanel$isChanged.
A more robust solution would be to have a property on your usercontrol (eg 'ClientIdOfHiddenField') that you set from your parent page on page_load
protected void Page_Load(object sender, EventArgs e)
{
UserControl1.ClientIdOfHiddenField = isChanged.ClientID;
}
then in the markup of your user control you can have
var element = document.getElementById("<%= ClientIdOfHiddenField %>");
Register like as below
isChanged.ClientID- is serverside property... so this will work for you
document.getElementById("<%=isChanged.ClientID %>");
If you are using jQuery you should be able to use
var hidden = $('input[id$="isChanged"]');
otherwise #Pranay Rana's answer should work.

Jquery Hidden Field in Table

I was wondering if anyone knew of a way to access a hidden field (by client id) within a table row using jquery.
$("#tblOne").find("tr").click(function() {
var worker = $(this).find(":input").val();
});
I find that the above works for a row that has only one input, but I need some help figuring out a way to get the value by the inputs name.
Here's the example of a table row. How would I access the two fields by their id's?
<table id="tblOne">
<tr>
<td>
<asp:HiddenField id="hdnfld_Id" Text='<% Eval("ID") %>'></asp:HiddenField>
</td>
<td>
<asp:HiddenField id="hdnfld_Id2" Text='<% Eval("ID2") %>'></asp:HiddenField>
</td>
</tr>
</table>
I normally use a positive lookup to match the id, this method avoids requiring the client id
(id contains foo)
$(this).find("input[id*='foo']").val();
With the way you have it setup right now, you could do this:
$('tr td', '#tblOne').eq(0).find(':input').val(); // find input in 1st TD
$('tr td', '#tblOne').eq(1).find(':input').val(); // find input in 2nd TD
Using this you don't have to worry about the input's ClientID.
You could do it like this:
$("#tblOne").find("tr").click(function() {
var election = $(this).find("td").eq(0).html();
var worker = $(this).find('input[name=theName]').val();
});
Read through this excellent article 'How to get what you want using jQuery' by Benjamin Sterling.
Why don't you simply use this:
jQuery("#<%=hdnfld_Id.ClientID%>")
<asp:HiddenField id="foo"> generates an <input type="hidden" id="foo"/> does it not? Why don't you just do
$("#foo").val()
?
I think you need to explain what you're trying to do a bit better. If you find that
$(this).find(":input").val();
... only works when you have one input, maybe what you're looking for is this:
$(this).find(":input").each(function() {
// Prints the value of each input.
alert($(this).val());
}
But as it stands, your question is not very clear. Try editing your question and take your time to explain exactly what you want.
Not an answer, but I was having incredible difficulty in pulling a hidden field value from within a table cell (using tablesorter on that table of course), so I am so happy to have found this line of code:
$(this).find(":input").val();
and it works wonderfully.
I also use the ".live" function, so it works even on huge tables.
THANK YOU!!!
HLR
I have three tabs each with a Submit button causing post backs. After the click event for the submit button, I want the current tab to persist.
Step 1.
Added an asp:HiddenField inside the tabs div ('tabs' div holds all the three divs that have the content for my tabs).
<asp:HiddenField ID="sel_tab" Value="" runat="server" />
Step 2.
Updated the value of sel_tab with the click event of each button that causes a post back.
protected void cmdSaveDailyMeasure_Click(object sender, EventArgs e)
{
sel_tab.Value = "0";
}
protected void cmdSaveWeeklyMeasure_Click(object sender, EventArgs e)
{
sel_tab.Value = "1";
}
protected void cmdSaveMonthlyMeasure_Click(object sender, EventArgs e)
{
sel_tab.Value = "2";
}
Step 3.
In my .js file I have the following code
// Tabs
$(document).ready(function() {
var iSelectedTab = $(this).find("input[id*='sel_tab']").val();
if (iSelectedTab == null)
iSelectedTab = 0;
$('[id$=tabs]').tabs({ selected: iSelectedTab });
});
This works even if you are using Master Pages (i am). Don't need the <%=foo.ClientID%> part.

Categories