asp.net programmatically get text inside dynamic div - javascript

I'm trying to get the text of a div on creating dynamically in asp.
below is an example of the html table created by my datagrid:
<table border="1" id="MainContent_dgValues" style="border-collapse:collapse;">
<tbody><tr>
<td>Date Modified<td>Comment</td><td></td>
</tr><tr>
<td>3/26/2000</td><td id="myEdit" onclick="makeEditable()">My Text</td><td>Update</td>
</tr><tr>
</tr>
</tbody></table>
This is the code I have for my div created dynamically:
<script >
function makeEditable() {
var divTag = document.createElement("div");
divTag.setAttribute("id", "editdiv");
divTag.setAttribute("runat", "server");
divTag.setAttribute("contenteditable", "true");
var s = document.getElementById("myEdit").innerHTML;
document.getElementById("myEdit").innerHTML = "";
var mytext = document.createTextNode(s)
divTag.appendChild(mytext);
document.getElementById('myEdit').appendChild(divTag);
document.getElementById('myEdit').removeAttribute("onclick");
}
</script>
This creates a contenteditable div inside the td where it says My Text
Once the update on the table is clicked, I then wish to grab the text within the div in my code:
protected void dgValues_EditCommand(object source, DataGridCommandEventArgs e)
{
// Get div text here
}
Please help.

Since DIV is client-side only, as it is you cannot pass it to backend code. What you can do is on update click first catch a client-side click event and copy content of the DIV into hidden field. Then when form posts back - content of the hidden field will be available to the server-side code.

Thanks, I was able to do it, but there was a bit more work needed. In short, I populating a asp data grid and I would like to have where the use clicks on a td (generated by the data grid), they would be able to edit the contents.
I used HTML5's contenteditable however, its not compatible with IE 10 inside a td. So using the code and the answer suggested above, I made a div when the td was clicked using js. I then had trouble copying the contents of the div to a hidden input before my edit button within the data grid submitted. The following is the extra steps needed to do it.
<input enableviewstate="false" id="myComment" type="hidden" runat="server" />
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
/**
Create a script when a submit occurs, grabs div and places the text to a hidden input.
**/
string scriptKey = "OnSubmitScript";
string javaScript = "var divTag = document.getElementById('editdiv'); var hiddenInputTag = document.getElementById('MainContent_myComment'); hiddenInputTag.setAttribute('value', divTag.innerHTML); ";
this.ClientScript.RegisterOnSubmitStatement(this.GetType(), scriptKey, javaScript);
}
}
protected void dgValues_EditCommand(object source, DataGridCommandEventArgs e)
{
// Now gets the hidden input value
String newComment = myComment.Value;
}

Related

Focus on First asp:textbox in each bootstrap tab when clicking tab link

i am new to development and started developing a simple asp.net application. I am using bootstrap tabs having some asp labels and textboxes in each. I want focus on first textbox in the tab content when click on that tab. I searched various answers but all are for input fields(exp: input type="text"). can't find any for asp textbox. Any help will be appreciated.
Thanks
ASP.NET TextBoxes are HTML textboxes. By default, the ClientIDMode of controls are Predictable. This means the rendered HTML's id is auto-generated.
// ASP.NET TextBox
<asp:TextBox ID="TextBox1"/>
// Rendered HTML
<input type="text" id="ContentPlaceHolder1_TextBox1_1"/>
What you can do is add ClientIDMode="Static" to the TextBox. This will make the rendered (HTML) id of the input the same as the ID you passed to the TextBox.
// ASP.NET TextBox
<asp:TextBox ID="TextBox1" ClientIDMode="Static"/>
// Rendered HTML
<input type="text" id="TextBox1"/>
You can then target that via JavaScript using the answers you've searched for.
EDIT:
If you don't want to target the TextBoxes via id, you can probably just use CSS classes to tag them like:
<asp:TextBox ID="TextBox1" CssClass="default-focus" />
Then with jQuery:
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var target = event.target.attributes.href.value;
var $textbox = $(target + ' .default-focus');
$textbox.focus();
});
There is another way to achieve this though its longer but worked for me.
In this solution we can search which navbar tab we are currently in and then set focus to this tabs contents first text box by using its id.
code:
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e)
{
var target = e.target.attributes.href.value;
if (target == "#tab1")
{
$("#<%=txttab1.ClientID%>").focus();
}
else
{
if (target == "#tab2")
{
$("#<%=txttab2.ClientID%>").focus();
}
else
{
if (target == "#tab3")
{
$("#<%=txttab3.ClientID%>").focus();
}
}
}
}

Can't get text Area value in export to excel and also in printing page

I am using ASP.NET MVC 4 and html with razor engine. Upon my project requirement I have to print the values inside the table and also export it into excel. I m using the JavaScript code as follows :
function exportbtn() {
debugger;
var chk = FCDdata.outerHTML;
$("#idhdnfield").val(chk);
}
Then in my controller I get the value of hidden field and then export it to excel.
Response.Clear();
Response.AppendHeader("content-disposition", "attachment;filename=Crewdata.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.Write(hdnfield);
Response.End();
My problem is , there s a column in my table where I have to display many values. So I used text area in my td.
<td> <textarea>My value </textarea> </td>
But this value is left blank in my excel sheet and also the print page shows the first visible line with scroll and not the whole values inside td. Can you please advise what needs to be done?
Probably your textarea value has line breaks. So try to send the data with linebreaks removed i.e.
function exportbtn() {
debugger;
var chk = FCDdata.outerHTML;
$("#idhdnfield").val(chk.split("\n").join("").split("\r").join(""));
}

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.

Hiding/Showing an html table with C# and 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.

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