I would like to return text label in my gridview with Jquery
<div class="risksContainer">
<div class="risksGrid">
<asp:GridView ID="GridViewRisks" runat="server"
[...]
/>
<Columns>
<asp:TemplateField HeaderText="...">
<ItemTemplate>
<div class="CodeProductColumn">
<asp:Label ID="IDRisk" runat="server" CssClass="IDRiskIndex" Text="<%# Item.ID_Risk %>" />
<asp:Repeater ID="LabelRepeatCodeProduct" runat="server"
[....]
</asp:Repeater>
</div>
</ItemTemplate>
I try many solutions, but i don't know how i get the label Text of my selected row.
javascript :
function blabla(){
var Id_risk = $(".risksContainer .risksGrid .IDRiskIndex").text();
alert("Id_risk =" + Id_risk );
return Id_risk ;
}
(this function start when i click on edit button in my row)
I get text of all rows in my gridview and not only my selected row.
I try with "parent, child, first, selected, rows[]...
I am beginner and i'm desperate to find it
Use try in JavaScript:
<script type="text/javascript">
function blabla()
{
// find gridview
var gv = document.getElementById("<%=GridViewRisks.ID %>");
// get row count
var gvRowCount = gv.rows.length;
var i = 1;
for (i; i<= gvRowCount - 1; i++)
{
// get label value from column 2
alert(gv.rows[i].cells[2].childNodes[1].innerHTML);
}
return false;
}
</script>
<asp:Button ID="Button1" runat="server" OnClientClick=" blabla();return false;" ... />
Assuming you set the selected row in code behind with GridViewRisks.SelectedIndex = i, you can set the CSS class of the selected row.
<asp:GridView ID="GridViewRisks" runat="server" SelectedRowStyle-CssClass="selectedRow">
Now you can use that class to get the correct row in jQuery.
var Id_risk = $(".selectedRow .IDRiskIndex").text();
Related
I'm trying to find the text of a label within row of an asp.net grid view when anywhere on the row is clicked. I have the gridview shown below with the jquery I'm using underneath. I'm getting a javascript alert box when I click on the row, just no text. What am I doing wrong?
<asp:GridView runat="server" ID="grvAgents" AutoGenerateColumns="False" OnRowDataBound="grvAgents_OnRowDataBound"
CssClass="table table-bordered table-striped" AlternatingRowStyle-CssClass="even"
ClientIDMode="Static">
<AlternatingRowStyle CssClass="even" />
<Columns>
<asp:TemplateField HeaderText="Site" Visible="false">
<ItemTemplate>
<asp:Label ID="lblSite" CssClass="siteLbl" runat="server" Text='<%#Eval("Site") %>' ClientIDMode="Static"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<script type="text/javascript">
function BindEvents() {
$(document).ready(function (e) {
$('#grvAgents tr').click(function () {
var tr = $(this).closest('tr');
var lbl = tr.find('.siteLbl').text();
alert(lbl);
//
});
});
}
</script>
I don't see a reason why your code should not work. However you can try the alternative by referencing the label with the id instead of the class name.
$(function ()
{
$('#grvAgents tr').click(function () {
var lbl = $(this).closest('tr').find('span[id*="lblSite"]').text();
alert(lbl);
});
});
Try This
$(function ()
{
$('#grvAgents tr').click(function () {
alert($(this).find('.siteLbl').text());
});
});
Because you set the TemplateField Visible="false",so it cannot be find in the output html.
You can hide the control by css:
STYLE
<style type="text/css">
.hid
{
display:none;
}
</style>
TemplateField
<asp:TemplateField HeaderText="Site" HeaderStyle-CssClass="hid" ItemStyle-CssClass="hid">
Try it again.
I Have added the validation of a TextBox inside this GridView, but this validation is only working on the current page of the GridView (it is not working on the previous and next pages of the GridView).
<asp:GridView ID="Grd1" runat ="server" Width ="100%" AllowPaging ="true" pagesize="5">
<Columns>
<asp:BoundField HeaderText="Name" DataField="NM" ItemStyle-Width="300px" HeaderStyle-Width="300px" HeaderStyle-Wrap="false" ItemStyle-Wrap="false" />
<asp:TemplateField HeaderText="Size (GB)">
<ItemTemplate>
<asp:TextBox ID="txtSize" runat="server" Width="100px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnAdd" runat="server" Text="Save" OnClick="btnAdd_Click" />
<script language="javascript" type="text/javascript">
function IsValidateAdd() {
if (validateGridTextBox() == false)
{ return false; }
}
function validateGridTextBox() {
var flag = false;
var dropdowns = new Array(); //Create array to hold all the dropdown lists.
var gridview = document.getElementById('<%=Grd1.ClientID %>'); //grvDMODetails is the id of ur gridview.
dropdowns = gridview.getElementsByTagName('input'); //Get all dropdown lists contained in Grd1.
for (var i = 0; i < dropdowns.length; i++) {
if (dropdowns.item(i).value != "") //If dropdown has no selected value
{
flag = true;
}
else
{
flag = false;
break;
}
}
if (flag == false)
{
alert('Please enter Table Size.');
return flag;
}
</script>
Code behind:
btnAddDM.Attributes.Add("onclick", "return IsValidateAdd();");
when you navigation thru prev page or next page,the grid view part has changed,but the javascript function was binded to the original grid view.this is why it does not work.
If you want it work,there are 2 solutions
1,when you navigation to other pages,bind the javascript validate function again manually.
2,add onclientclick attribute to the textbox control,such as
<asp:TextBox ID="txtSize" runat="server" Width="100px" onClientClick="validateGridTextBox(this)"></asp:TextBox>
and change your validateGridTextBox javascript function accordingly.
I have a checkbox template field within a gridview in c#, this field also has a hidden field with the id behind it. I want to use jQuery to raise an event on click of the checkbox to grab a datakey value so I can run a query through jQuery and add the checked item to the database. I have seen examples that get datakeys when an overall button is clicked but I want this to happen on each checkbox clicked within the gridview. I currently get "undefined" when trying to access the id.
C# within the gridview
<ItemTemplate>
<asp:CheckBox ID="CheckBox" CssClass="checkbox" runat="server" />
<asp:HiddenField ID="idnum" runat="server" Value='<%# Eval("id") %>' />
</ItemTemplate>
jQuery
$(document).ready(function () {
var gridResults = document.getElementById('<%= grdResults.ClientID %>');
$("form input:checkbox").click(function (e) {
var id = $(this).next('#idnum').val();
alert(id);
return false;
});
});
If there are multiple fields with ID="idnum" you should probably change that to class="idnum". After adding the class you could get the value using:
var gridResults = $(e.target).next('.idnum').val();
If idnum is just an example which is different for each field, you can just use var id = $('#idnum').val();
EDIT: changed e.target.next('.idnum').val(); to $(e.target).next('.idnum').val(); to convert the element to jQuery object
//This is the script to get datakeyname value on check box check event inside GridView
<script type="text/jscript">
$(document).ready(function () {
var gridResults = document.getElementById('<%= grdCateogry.ClientID %>');
$("form input:checkbox").click(function (e) {
var id = $(this).next($('#IDVal')).val();
alert(id);
return false;
});
});
</script>
//This is the GridView
<asp:GridView ID="grdCateogry" DataKeyNames="CategoryId" runat="server">
<Columns>
<asp:TemplateField HeaderText ="Try" ItemStyle-Width="20px">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
<asp:HiddenField ID="IDVal" runat="server" Value='<%# Eval("CategoryId") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
i have a gridview which has a checkbox column. The header is of this column is a checkbox.
When it is checked all the values get checked and vice-verse.
I do this using javascript.
The problem is if i check it and perform any other event on the page which requires a postback the checked values disappear. I dont want them to disappear.
here is my code:
<script type="text/javascript">
function checkAllBoxes() {
//get total number of rows in the gridview and do whatever
//you want with it..just grabbing it just cause
var totalChkBoxes = parseInt('<%= GridView1.Rows.Count %>');
var gvControl = document.getElementById('<%= GridView1.ClientID %>');
//this is the checkbox in the item template...this has to be the same name as the ID of it
var gvChkBoxControl = "Select_CheckBox";
//this is the checkbox in the header template
var mainChkBox = document.getElementById("chkBoxAll");
//get an array of input types in the gridview
var inputTypes = gvControl.getElementsByTagName("input");
for (var i = 0; i < inputTypes.length; i++) {
//if the input type is a checkbox and the id of it is what we set above
//then check or uncheck according to the main checkbox in the header template
if (inputTypes[i].type == 'checkbox' && inputTypes[i].id.indexOf(gvChkBoxControl, 0) >= 0)
inputTypes[i].checked = mainChkBox.checked;
}
}
</script>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<input id="chkBoxAll" type="checkbox" onclick="checkAllBoxes()"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="Select_CheckBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<!-- The rest of your rows here -->
</Columns>
</asp:GridView>
Thanks for the help.
Make your checkbox a server-side control that uses the view state by adding runat="server". It will then maintain its value across post backs.
<input id="chkBoxAll" type="checkbox" onclick="checkAllBoxes()" runat="server"/>
And change your JavaScript to select the id that ends in chkBoxAll. I use jQuery in the example below:
//this is the checkbox in the header template
var mainChkBox = $('input[id$="chkBoxAll"]');
However, if you sort your gridview rows or use paging, you will likely come across less friendly behavior.
I have a GirdView in Edit Mode with inside a TextBox.
I need to Retrieve this TextBox with ID (from the source code in the browser) in JavaScript.
ctl00$MainContent$uxListOptions$ctl02$uxValueInput
But I receive an error because my JavaScript is not able to find the TextBox.
Here is the code:
<span onclick="encodeMyHtml('<%# UniqueID.Replace("$", "_") %>_FormViewContentManager_ContentTextBox')">
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="[Publish]" />
</span>
In my control’s OnPageLoad I call this:
private void addEditorJavaScript()
{
// create our HTML encoder javascript function
// this way it shows up once per page that the control is on
string scr = #"<script type='text/javascript'>function encodeMyHtml(name){
var content = document.getElementById(name).value
content = content.replace(/</g,'<');
content = content.replace(/>/g,'>');
document.getElementById(name).value = content;
}</script>";
// add the javascript into the Page
ClientScriptManager cm = Page.ClientScript;
cm.RegisterClientScriptBlock(this.GetType(), "GlobalJavascript", scr);
}
I am trying to use this code http://dustyreagan.com/how-to-submit-html-without-disabling/
Any Idea what am I doing wrong? Thanks guys!
If you are using ASP.Net 4.0, you could use ClientIdMode=Static or Predictable for this control.
encodeMyHtml('<%# UniqueID.Replace("$", "_") %>_FormViewContentManager_ContentTextBox')
This will result in
encodeMyHtml('ctl00_MainContent_uxListOptions_ctl02_uxValueInput_FormViewContentManager_ContentTextBox')
Does a control of that ID exist in your DOM?
It seems that you're making a lot of assumptions as to how the ID's will be created. It would be better to immediately reference the ContentTextBox.ClientID.
Something like the following, provided that ContentTextBox is a valid reference to the text box:
encodeMyHtml('<%# ContentTextBox.ClientID %>')
You can define your grid like this :
<div>
<asp:GridView ID="GridView1" runat="server" Width = "550px"
AutoGenerateColumns = "false" Font-Names = "Calibri"
Font-Size = "12pt" HeaderStyle-BackColor = "LightYellow" AllowPaging ="true" ShowFooter = "true" OnPageIndexChanging = "OnPaging" PageSize = "10" >
<Columns>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText = "Name">
<ItemTemplate>
<asp:TextBox ID="txtPeriod" runat="server" CssClass="css1 mycss" Text='<%# Eval("Period")%>'
onblur="SetPostingPeriod(this)"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
</div>
And your Javascript Function Would be :
<script language="javascript" type="text/javascript">
/* Populating same data to all the textboxes inside grid,
once change of text for one textbox - by using jquery
*/
function SetPostingPeriod(obj) {
var cntNbr = $("#" + obj.id).val();
// var cntNbr = document.getElementById(obj.id).value;
// alert(cntNbr);
//Access Grid element by using name selector
$("#<%=GridView1.ClientID %> input[name*='txtPeriod']").each(function (index) {
if ($.trim($(this).val()) != "")
if (!isNaN($(this).val())) {
$(this).val(cntNbr);
}
});
}
</script>
This Javascript function is called onblur event of the textbox.
When this function is called at the same time it passes a parameter
which is nothing but the textbox id.
Inside javascript function by using the parameter which is the
id of the textbox we are getting the vaue.
Here is the code :
var cntNbr = $("#" + obj.id).val();
Then For each of the "txtPeriod" controls available inside the grid, we need to assign
the value of current "txtPeriod" textbox value to them.
Looping Grid to identify each "txtPeriod" available :
Here is the code :
$("#<%=GridView1.ClientID %> input[name*='txtPeriod']").each(function (index) {
});
Inside this loop we need to assign the "txtPeriod"(current/Modified) value to other
"txtPeriod" textboxes.Before assign its good practice to check is it null or NAN.
Here is the code :
if ($.trim($(this).val()) != "")
if (!isNaN($(this).val())) {
$(this).val(cntNbr);
}