Jquery Hidden Field in Table - javascript

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.

Related

asp.net programmatically get text inside dynamic div

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;
}

how to get values of jquery select2 tags list using asp.net?

i want to get select values of jquery select2 plugin in asp.net code behind.
Here is my source
Client Side:
<select id="ddlcountry" runat="server" class="select" style="width: 100%;">
</select>
Code Behind:
var query1 = from pcountry in CTX.Countries
orderby pcountry.Country1 ascending
select new
{
pcountry.CountryId,
pcountry.CountryName
};
if (query1 != null)
{
ddlcountry.DataSource = query1.ToList();
ddlcountry.DataValueField = "CountryId";
ddlcountry.DataTextField = "CountryName";
ddlcountry.DataBind();
ddlcountry.Multiple = true;
}
protected void btnSave_Click(object sender, EventArgs e)
{
Now i want to get all the selected country values here ?
}
Please help me,i will be very thankful.
If you're not creating the <select> element as an <ASP:DropDownList> control, then I don't believe you will have access to properties and methods such as "Datasource", etc. You can, however, access HTML elements that have the runat="server" attribute added.
I believe the <option> tag is of the generic HTML control type. I stick to VB.Net, so I'll have to write some psuedo code for you...
For each o as HtmlGenericControl in ddlcountry.Children.ofType(of HtmlGenericControl)
If o.Attributes("selected") then
' Here you can access your option value using the "value" attribute (and InnerHtml works too, I think)
End if
Next o
Here's a link to an answer where I showed how to loop through generic controls using a working example:
how can I get HTML attribute from ASP/VB.net code-behind
Thanks Lopsided,i appreciate your kind help.I tried this but it doesn't work for me.
According to your answer i thought some solution,should i get the select2 option list value in client side and store it into hiddenfield and then i get the hidden field value into server side code?
You can just loop through the items collection to find out which countries have been selected.
foreach (ListItem li in ddlcountry.Items) {
if ((li.Selected)) {
//Selected Country
}
}

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.

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.

How do I get a textbox with particular ValidationGroup in jQuery?

I have an ASP.NET TextBox ID="txtDate" in my usercontrol. It has ValidationGroup="MyUC" set. Now my UC is inside a Repeater Control. So there will be multiple instances of the same textbox.
I am able to get all textboxes like: $("[id$='_txtDate']");
Each of the txtDate will have a separate ValidationGroup assigned to it, dynamically.
So I want to get a textbox based on the id + ValidationGroup using jQuery / javascript.
How can it be done? Any guidance really appreciated.
Edited based on Josiah's Reply and the way I found:
Sorry, my scenario is kind of complicated to include entire code. In short the textboxes are attached to jquery datepicker and the code below runs when a date is selected. The same handler is attached to multiple textboxes. Here is what I have:
var valgrp="MyGroup"; /*this mygroup is dynamic but keeping static for e.g.*/
var txtdate1 = $("[id$='txtDate']").filter(function(){if(this.Validators!=null){return this.Validators[0].validationGroup == valgrp;}});
var txtdate2 = $("[id$='txtDate']").filter(function(){return this.validationGroup == valgrp;});
alert("date1- " + txtdate1.val()); /*this returns date selected from datepicker*/
alert("date2 " + txtdate2.val()); /*this returns empty*/
Depending on the date I want to do something else. So txtdate1 is currently working for me where I don't have to add class to my textbox. I was playing with the txtdate2 which isn't behaving how I was expecting and so I had to post this question.
Here is a sample test to see this.validationGroup not returned:
$(function () {
$("#btntest").click(function () {
$("[id$='txtDate']").each(function () {
alert(this.validationGroup);//returns undefined
alert(this.Validators[0].validationGroup); //returns "test"
});
});
});
<input id="btntest" type="button" value="button" />
<asp:TextBox ID="txtDate" runat="server" ValidationGroup="test"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Text="*" ErrorMessage="Required." ControlToValidate="txtDate" ValidationGroup="test"></asp:RequiredFieldValidator>
While Josiah's solution didn't work but his idea of attaching class to textbox could have been a potential solution. Since it didn't exactly fit my needs I would answer my own question. Here is the solution I came up with:
var valgrp="MyGroup"; /*this mygroup is dynamic but keeping static for e.g.*/
var txtdate1 = $("[id$='txtDate']").filter(function(){if(this.Validators!=null){return this.Validators[0].validationGroup == valgrp;}});
The above returns me the textbox I am looking for. The key is
this.Validators[0].validationGroup
It gets the validationGroup of the first validator control attached to the textbox (this).
From a few searches, the validation group is stored as a property on the Form Element.
So you can add a class selector like so:
$("[id$='_txtDate']").each(function(){
var group = this.validationGroup,
$this = $(this);
if(!$this.hasClass('validationgroup'))
$this.addClass('validationgroup ' + group);
});
Of course if you have a repeater you will need to run this code each time an row is repeated. But now you can select fields by validation group like this:
$('.validationgroup.[group name]')
I don't use jQuery, but I'd think it would be:
$("#txtDate[ValidationGroup='MyUc']")
since jQuery's selectors are based on CSS. That works with document.querySelector, unless having more that one element with the same id is causing problems.

Categories