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

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

Related

Execute function when the checkbox is checked

I have below function when we check or uncheck the check box (inside the gridview) it will show the popup and other processing information.
Is there any way to execute this function only when checkbox is checked and not on unchecked condition?
Below is my function:
$(document).ready(function () {
$('#<%= gvPRCertInfo.ClientID %> input[type="checkbox"]').change(function () {
var signValue = $(this).closest('tr').children('td:eq(4)').html();
if (signValue == "Virtual") {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("you have selected virtual do u want to create a new name for this?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
});
});
This is my gridview:
<asp:GridView ID="gvPRCertInfo" runat="server" GridLines="None"
CssClass="data responsive">
<Columns>
<asp:TemplateField HeaderText="Select" SortExpression="">
<HeaderTemplate>
<asp:CheckBox ID="chkboxSelectAll" runat="server" AutoPostBack="true" OnCheckedChanged="chkboxSelectAll_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkCert" AutoPostBack="true" ClientIDMode="Static" OnCheckedChanged="chkCert_CheckedChanged" runat="server" />
<input type="hidden" id="hdnCertId" runat="server" value='<%# DataBinder.Eval(Container.DataItem, "CertId") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CertificateID" HeaderText="Certificate ID" HeaderStyle-HorizontalAlign="Center" />
................
.................
Would anyone please suggest any ideas on how to execute only when I check the checkbox.
Try this inside the on change function of the checkbox.
if($(this).is(':checked') == true)
{
/* Your function code here.*/
}
hello my dear i think this will work but still i'm not sure
you can code like below :
$(document).ready(function () {
$('#myCheckbox').change(function () {
if ($(this).attr("checked")) {
// fire your function
return;
}
// not checked
});
});
try this in side the onchange function
Javascript code
if(document.getElementById('mycheckbox').checked) {
console.log("ckecked")
} else {
console.log("not ckecked")
}
jquery code
if ($('#mycheckbox').attr("checked")) {
console.log("ckecked")
}else{
console.log("not ckecked")
}
You can use jQuery's is() function:
if($("input").is(':checked')) {
dosomething
}

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 check/uncheck Gridview check box for outside button

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

How to save the selected value of checkboxlist in array?

I want to save the values of checkbox in an array using javascript or jquery.
My checkboxlist is inside the datalist. Whenever the user select an item, I want to add the value of that selected item to a array.
ASPX :
<asp:DataList ID="dl_Groups_1" RepeatColumns="1" runat="server" OnItemDataBound="dl_Groups_1_ItemDataBound" RepeatDirection="vertical" ShowFooter="False" ShowHeader="False">
<ItemTemplate>
<asp:CheckBox Font-Bold="true" runat="server" ID="chk_Group_1" Text='<%# Eval("category_type") %>' Value='<%# Eval("service_type_category_id") %>' onclick="OnGroupClick" />
<asp:CheckBoxList CssClass="line" runat="server" ID="chkServiceType_1" DataValueField="ServiceTypeID" DataTextField="Name" EnableViewState="true">
</asp:CheckBoxList>
<br />
</ItemTemplate>
</asp:DataList>
I tried the below to, get the items that are slected, but i am struck up here...
function test() {
$(":checkbox").each(function () {
if (this.checked) {
alert(this);
}
});
}
When i do this, i get alert message as "ON" and not the value. And where do i call the javascript to keep the array updated on selecting and un selecting the items in checkboxlist ?
var arrValues = new Array();
function test() {
$(":checkbox").each(function () {
if (this.checked && arrValues.indexOf(this.value) == -1) {
arrValues.push(this.value);
}
});
}
use map()
var selectedValue= $("input:checkbox:checked").map(function(){
return this.value;
}).get();
console.log(selectedValue);
selectedValue will have all the checked value in array..
var val;
$('#<%= chkServiceType_1.ClientID %> input[type=checkbox]').change(function(){
val = $("#<%= chkServiceType_1.ClientID %> input[type=checkbox]:checked").map(function(){
return this.value;
}).get();
})

Categories

Resources