How to check/uncheck Gridview check box for outside button - javascript

How do I toggle the gridview check box from a button? I want to use Javascript only.
I am using below code for grid view:
<asp:GridView ID="gvWrkLogVW" runat="server" AutoGenerateColumns="False" GridLines="None" BorderStyle="None" ShowHeader="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkWorklog" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="The_Text" />
</Columns>
</asp:GridView>
I want to access the code gridview checkbox from external button
<asp:Button ID="btncheck" runat="server" Text="Check All" OnClientClick="SelectAll()" />
I am writing the below javascript but it is not working
function SelectAll() {
var gridViewControl = document.getElementById('<%= gvGetAllCircuits.ClientID %>');
for (i = 0; i < gridViewControl.rows.length; i++) {
if (gridViewControl.elements[1].type == "checkbox") {
gridViewControl.elements[1].checked = true;
}
}
}

JS
function SelectAll() {
var gridViewControl = document.getElementById('<%= gvGetAllCircuits.ClientID %>');
for (i = 0; i < gridViewControl.rows.length; i++) {
//loop starts from 1. rows[0] points to the header.
for (i=1; i<gridViewControl.rows.length; i++)
{
//get the reference of first column - if you have a header
cell = gridViewControl.rows[i].cells[0];
//loop according to the number of childNodes in the cell
for (j=0; j<cell.childNodes.length; j++)
{
//if childNode type is CheckBox
if (cell.childNodes[j].type =="checkbox")
{
//assign the status of the Select All checkbox to the cell checkbox within the grid
cell.childNodes[j].checked = "true";
}
}
}
}
}

Related

Jquery each function not execute inside gridview textbox in asp.net

Here is my gridview
<asp:GridView ID="gvDoctorVisits" runat="server" DataKeyNames="AdmissionId" class="tableStyle"
AutoGenerateColumns="False" Width="100%" EmptyDataText="No record found" ShowHeaderWhenEmpty="true">
<Columns>
<asp:BoundField DataField="Amount" HeaderText="Amount"></asp:BoundField>
<%--<asp:BoundField DataField="PaidAmount" HeaderText="Paid Amount"></asp:BoundField>--%>
<asp:TemplateField HeaderText="Paid Amount">
<ItemTemplate>
<asp:TextBox ID="txtPaidAmount" type="text" runat="server" Text='<%# Eval("PaidAmount") %>' CssClass='<%# "txtDoctorPaidAmount "+"txtDPPaidAmount_"+Eval("AdmissionId") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am using j query each function of my gridview textbox class,but jquery each function not executing,here is my code
$(".txtDoctorPaidAmount").on('keyup change', function () {
debugger;
var sum = 0;
$('.txtDoctorPaidAmount').each(function () {
sum += parseFloat($(this).text());
});
$("#txtPaidAmount").val(sum.toFixed(2));
});
this each function not executing,how to solve this?
Try this: Use val() instead of text() and add a console.log to see, if iteration is executed.
$(".txtDoctorPaidAmount").on('keyup change', function () {
var sum = 0;
$('.txtDoctorPaidAmount').each(function () {
// use val instead of text
let inputVal = $(this).val();
// this line is just to show, that each is executed
console.log('adding value: ' + inputVal);
sum += parseFloat(inputVal);
});
$("#txtPaidAmount").val(sum.toFixed(2));
});

Save state of gridview when using JavaScript filtering in asp.net c#

I'm using javascript to filter my gridview and it works great. The problem is when I click on the gridview to edit an item, it postback and the filtered table is now unfiltered. How can I keep the state of the gridview when using the javascript filter?
Javascript:
<script type="text/javascript">
function myFunction() {
//Searcing the table
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("<%=txtSearch.ClientID %>");
filter = input.value.toUpperCase();
table = document.getElementById("<%=gridList.ClientID %>");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td");
if (td.length > 0) { // to avoid th
//Search the specific column
if (
td[0].innerHTML.toUpperCase().indexOf(filter) > -1 ||
td[1].innerHTML.toUpperCase().indexOf(filter) > -1 ||
td[2].innerHTML.toUpperCase().indexOf(filter) > -1 ||
td[3].innerHTML.toUpperCase().indexOf(filter) > -1 ||
td[4].innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
ASP:
<asp:TextBox ID="txtSearch" runat="server" class="form-control" Visible="true" Width="250px" placeholder="Enter Search Term..." onkeyup="myFunction()"/>
<asp:GridView ID="gridList" runat="server" HorizontalAlign="left" ShowHeader="True" AutoGenerateColumns="false" GridLines="None"
OnRowEditing="gridList_RowEditing" OnRowCancelingEdit="gridListt_RowCancelingEdit" OnRowUpdating="gridList_RowUpdating">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="left" HeaderText="User">
<ItemTemplate>
<asp:Label ID="user" Visible="true" runat="server" Text='<%# Eval("User") %> ' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtUser" class="form-control" runat="server" Text='<%# Eval("User") %> '></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" HeaderText="Modify"
EditText="<span style='font-size: 20px; color: #27ae60;'><span class='glyphicons glyph-edit'></span></span>"
DeleteText="<span style='font-size: 18px; color: #c0392b;'><span class='glyphicons glyph-bin'></span></span>"
CancelText="<span style='font-size: 20px; color: #7f8c8d;'><span class='glyphicons glyph-remove-2'></span></span>"
UpdateText="<span style='font-size: 20px; color: #2980b9;'><span class='glyphicons glyph-floppy-saved'></span></span>" />
</Columns>
</asp:GridView>
c# editing a row for example:
protected void gridListt_RowEditing(object sender, GridViewEditEventArgs e)
{
gridListGiftList.EditIndex = e.NewEditIndex;
//I need to somehow load the filtered javascript state of the table here rather than the full table
DataSet dsList = objuser.GetList(0);
gridList.DataSource = dsList.Tables[0];
gridList.DataBind();
}
Assuming txtSearch is an ASP.NET control, it should retain its state on a postback. I'm assuming the search box doesn't get cleared out when you save a row.
Why not just run myFunction() on window.onload in addition to the button click event that already runs it.. Then add a conditional in it to check for blank search values before executing your code:
function myFunction() {
//Searcing the table
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("txtSearch");
filter = input.value.toUpperCase();
table = document.getElementById("gridList");
tr = table.getElementsByTagName("tr");
if (input.value != "") {
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td");
if (td.length > 0) { // to avoid th
//Search the specific column
if ( td[0].innerHTML.toUpperCase().indexOf(filter) > -1 ||
td[1].innerHTML.toUpperCase().indexOf(filter) > -1 ||
td[2].innerHTML.toUpperCase().indexOf(filter) > -1 ||
td[3].innerHTML.toUpperCase().indexOf(filter) > -1 ||
td[4].innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
else {
for (i = 0; i < tr.length; i++) {
tr[i].style.display = "";
}
}
}
window.onload = myFunction;
Assuming your txtSearch looks like this
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
Then you simply have to check in code behind if there is a PostBack and if the TextBox has a Value. Then use ScriptManager to execute myFunction() again. I've placed the code in Page_Load, but you could also place it in gridListt_RowEditing
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack && !string.IsNullOrEmpty(txtSearch.Text))
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "reFilter", "myFunction()", true);
}
}
However if you are doing self build sorting and filtering stuff on a html table, I would recommend looking into DataTables.net
Please try following.
There should be no post back on grid view.Even edit should happen through api methods via Ajax.
As someone mentioned use https://datatables.net/ it is a good approach. Instead of using gridview use api enabled solution
The other way is when you filter anything save it in a hidden field and read it from server side post back and implement same filtering from server side (harder way).
I cannot provide code at this time.But I had implemented it in past.

Searching Records from gridview based on value enterd into TextBox

I am trying to Search records from gridview with pagination, matching with the values entered into textbox, and its working quite fine. Issue is that it only show the records which are at first page , but not search the records from the next pages.
aspx code:
<asp:GridView ID="GrdFutureApt" AutoGenerateColumns="false" runat="server" CssClass="table table-responsive table-condensed table-bordered table-striped" AllowPaging="true"
CellPadding="4" ForeColor="#333333" GridLines="None" PageSize="5" OnPageIndexChanging="GrdFutureApt_PageIndexChanging">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PatientName" HeaderText="Patient Name" Visible="false"/>
<asp:BoundField DataField="DoctorName" HeaderText="Doctor Name"/>
<asp:BoundField DataField="AppointmentDate" HeaderText="Appointment Date" DataFormatString="{0:dd/MM/yyyy}"/>
<asp:TemplateField HeaderText = "Appointment Time" SortExpression="Time">
<ItemTemplate>
<asp:Label runat="server" ID="lblAppointmentTime" Text='<%# DisplayAs12HourTime(Eval("AppointmentTime")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="AppoinmentStatus" HeaderText="Status"/>
</Columns>
<PagerSettings Mode="NextPrevious" PreviousPageText="Previous" NextPageText=" Next" Position="Bottom" />
<PagerStyle BackColor="#889FA2" HorizontalAlign="Left" ForeColor="White" Font-Bold="true" />
</asp:GridView>
I have used Following script to perform this function.
<script type="text/javascript">
$(document).ready(function () {
$('#<%=txtSearchBox.ClientID %>').keyup(function (e) {
SearchGridData();
});
});
function SearchGridData() {
var counter = 0;
//Get the search text
var searchText = $('#<%=txtSearchBox.ClientID %>').val().toLowerCase();
//Hide No record found message
$('#<%=lblMsgFail.ClientID %>').hide();
//Hode all the rows of gridview
$('#<%=GrdAppointments.ClientID %> tr:has(td)').hide();
if (searchText.length > 0) {
//Iterate all the td of all rows
$('#<%=GrdAppointments.ClientID %> tr:has(td)').children().each(function () {
var cellTextValue = $(this).text().toLowerCase();
//Check that text is matches or not
if (cellTextValue.indexOf(searchText) >= 0) {
$(this).parent().show();
counter++;
}
});
if (counter == 0) {
//Show No record found message
$('#<%=lblErrorMsg.ClientID %>').show();
}
}
else {
//Show All the rows of gridview
$('#<%=lblErrorMsg.ClientID %>').hide();
$('#<%=GrdAppointments.ClientID %> tr:has(td)').show();
}
}
</script>
And using following javascript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
the data to fill gridview comes from the following function:
public void LoadGrid()
{
S011AppointmentBOL objBol = new S011AppointmentBOL();
//DataTable ptApt = new DataTable();
dtAppointment = S011AppointmentBLL.GetAll();
int patID = dtPatient.AsEnumerable().Where(x => x.Field<string>("RegistrationNo") == RegNo).Select(x => x.Field<int>("PatientID")).FirstOrDefault();
dtAppointment.Columns.Add("PatientName", typeof(string));
dtAppointment.Columns.Add("DoctorName", typeof(string));
for (int i = 0; i < dtAppointment.Rows.Count; i++)
{
string pFname = dtPatient.AsEnumerable()
.Where(x => x.Field<int>("PatientID") == Convert.ToInt32(dtAppointment.Rows[i]["PatientID"]))
.Select(x => x.Field<string>("FirstName")).FirstOrDefault();
string pLname = dtPatient.AsEnumerable()
.Where(x => x.Field<int>("PatientID") == Convert.ToInt32(dtAppointment.Rows[i]["PatientID"]))
.Select(x => x.Field<string>("LastName")).FirstOrDefault();
string dFname = dtDoctor.AsEnumerable()
.Where(x => x.Field<int>("DoctorID") == Convert.ToInt32(dtAppointment.Rows[i]["DoctorID"]))
.Select(x => x.Field<string>("FirstName")).FirstOrDefault();
string dLname = dtDoctor.AsEnumerable()
.Where(x => x.Field<int>("DoctorID") == Convert.ToInt32(dtAppointment.Rows[i]["DoctorID"]))
.Select(x => x.Field<string>("LastName")).FirstOrDefault();
dtAppointment.Rows[i]["PatientName"] = pFname + " " + pLname;
dtAppointment.Rows[i]["DoctorName"] = dFname + " " + dLname;
}
DataTable boundTable = new DataTable();
var query = dtAppointment.AsEnumerable().Where(x => x.Field<int>("PatientID") == patID).Select(x => x).OrderByDescending(x => x.Field<DateTime>("AppointmentDate"));
var t = query.Any();
if (t)
{
boundTable = query.CopyToDataTable<DataRow>();
}
GrdAppointments.DataSource = boundTable;
GrdAppointments.DataBind();
}
And On every keyup I don't want query to database that's why am using the Datatable to fill gridview
Any Help Appreciated.. Thanks
You have enabled paging for Gridview so it will bind only records from selected pages on client side.So you have to either disable paging or rewrite jquery search function by calling a webmethord to search entire records which can bind search results.

Restricting gridview row selection in asp.net using c#.net

I have textbox and gridview(checkbox in Itemtemplate) in my webform.
my requirement selecting checkbox in gridview must be restricted based on value given in textbox i.e if textbox value is 10 then i can only be able to check 10 rows in gridview.
Can anybody give me javascrit for this or any other easy way....
Thanks in advance..
my code is below...
<script type="text/javascript" >
function CheckBoxCount() {
var gv = document.getElementById("<%= GridView1.ClientID %>");
var inputList = gv.getElementsByTagName("input");
var textboxcount = document.getElementById("<%=txtId.ClientID %>").value;
var numChecked = 0;
for (var i = 0; i < inputList.length; i++)
{
if (inputList[i].type == "checkbox" && inputList[i].checked)
{
alert(numChecked);
if (numChecked < textboxcount)
{
inp[i].checked = false;
alert(numChecked);
}
numChecked = numChecked + 1;
}
}
}
</script>
I am trying in javascript
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate >
<asp:CheckBox ID="chb" runat="server" AutoPostBack="true" onClick="CheckBoxCount()" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I can't give you the JS right away but try doing it this way.
put a class on your text box and check box, And then:
<asp:CheckBox ID="chb" runat="server" AutoPostBack="true" onClick="CheckBoxCount()" CssClass="MyCheckBox" />
Then in the javascript add a function onClick of checkBox:
$('.MyCheckBox').onClick(function(){
var $allCheckBoxes = $('#GridView1').find('.MyCheckBox');
var checkedCheckBoxes = 0;
var allowedCheckBoxes = $('.NumberOfCheckBoxesClass').val();
$allCheckBoxes.each(
if($(this).Checked){
checkedCheckBoxes++;
}
);
if(checkedCheckBoxes > 10){
$(this).disable;
AND SHOW SOME MESSAGE letting the user know.
}
});
You obviously need a few more methods to disable all the
Let me know if you have any questiongs.

How to enable and disable CheckBox in the GridView using JavaScript?

I have a GridView "gvpodetails". In that I have two checkboxes one in the first column of the GridView and another one in the last column of the GridView.
I want to enable the second checkbox when the first checkbox is checked.
And I want to disable the second checkbox when the first checkbox is unchecked.
I have wirtten the following JavaScript.
var grid = document.getElementById('<%=gvPODetails.ClientID %>');
var PlannedQty = 0*1;
if(grid != null)
{
var Inputs = grid.getElementsByTagName('input');
for(i = 0;i < Inputs.length;i++)
{
var id=String(Inputs[i].id);
if(Inputs[i].type == 'text' && id.indexOf("txtPlannedQuantity")!=-1)
{
if(Inputs[i-2].type == 'checkbox')
{
if(Inputs[i-2].checked)
{
if(Inputs[i+2].value == "0.000")
Inputs[i+2].value = (parseFloat(Inputs[i].value) - parseFloat(Inputs[i+1].value))
else
Inputs[i+2].value = Inputs[i+2].value;
Inputs[i+2].disabled = false;
Inputs[i+3].disabled = false;
Inputs[i-1].disabled = false;
Inputs[i+6].disabled = false;// This is for Second CheckBox
}
else
{
Inputs[i+4].value="0.00";
Inputs[i+5].value="0.00";
Inputs[0].checked = false;
Inputs[i+2].disabled = true;
Inputs[i+3].disabled = true;
Inputs[i-1].disabled = true;
Inputs[i+6].disabled = true;// This is for Second CheckBox
}
}
}
}
}
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked='<%#Bind("Select") %>' onClick="CheckedTotal();" /></ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" onclick="CheckAll();" /></HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ED_f">
<ItemTemplate>
<asp:CheckBox ID="chkEDInclusive" runat="server" Checked = '<%#Bind("EDInclusive_f") %>' Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
These are my javascript and GridView source code.
I also has some textboxes in the template field columns. This condition is applicable to all the textboxes in the GridView.
But the TextBoxes are enabled and disabled properly except the last CheckBox.
I have given only the Source code for the two Checkboxes only.
How to enable and disable the last checkbox in the GridView when the first the CheckBox is checked and Unchecked?
I need all your suggestions please..
You should probably use event delegation. on the grid to do this.
This javascript assumes that your row tag name is 'tr' and that your second checkbox is input[1] when selecting all inputs of that particular row. If you need IE support you'd need to use your favorite event handling wrapper.
window.onload = function () {
var rowNodeName = 'tr',
firstInputClassName = 'foo';
document.getElementById('<%=gvPODetails.ClientID %>').addEventListener('change', function (e) {
if (e.target.type === 'checkbox' && e.target.className.match(firstInputClassName)) {
// Find parent row
var row = e.target.parentNode;
while (row.nodeName !== rowNodeName.toUpperCase()) {
row = row.parentNode;
if (!row) {
break; // In case we hit document
}
}
if (row) {
var inputs = row.getElementsByTagName('input');
inputs[1].disabled = !e.target.checked;
}
}
}, false);
}
This will handle change events on any input in the grid with a className of 'foo' as defined in the firstInputClassName variable. When triggered will walk up the dom tree to a node with a tagname equalling rowNodeName, select the inputs in that row and set the disabled status of the second input in that row opposite of the checked state of the input that triggered the event.

Categories

Resources