Position HTML div based on JSON information - javascript

I am creating a dashboard and I was able to save information to my database using jQuery, JSON, and a generic handler. Now, I was able to call back my database information using a WebService and JSON. My database information looks like this..
On document ready, I use this to retrieve the information from my table from JSON
$.ajax({
type: "Post",
contentType: "application/json; charset=utf-8",
url: "Webservices/RetrieveWidgets.asmx/GetWidgets",
dataType: "json",
success: function (response) {
var te = response;
function sortResults(prop, asc) {
te.d = te.d.sort(function (a, b) {
if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
});
}
sortResults('SortNo', true);
for (var i = 0; i < te.d.length; i++) {
$('#test ul').append('<li>' + te.d[i].Title + '</li>');
console.log(te.d[i])
}
},
error: function (repo) {
console.log(repo);
$("#console").html('<div class="fail">Dashboard could no load!</div>').css('visibility', 'visible').fadeTo(600, 1);
setTimeout(function () {
$('#console').delay(500).fadeTo(600, 0);
}, 1000);
}
});
I was helped with the above.. and for testing purposes, this was added to the HTML
<div id="test">
<ul>
</ul>
</div>
And this is what is displayed.
So what is happening, it's ordered by the SortNo and the title of the widgets are displayed. The first 3 are in SortNo 0, and so on. This has really helped me with passing the JSON. Here is what my dashboard looks like..
And this is what my aspx page looks like (only a single 'column' to get an idea)
<div class="column" id="column1" runat="server">
<div class="dragbox" id="CurrentDealsWidget" runat="server" visible="false">
<h2 style="font-size: 14pt">Current Deals per Location</h2>
<div class="dragbox-content">
<asp:GridView ID="gvCurrentLocationTotals" runat="server" AutoGenerateColumns="False"
DataKeyNames="InternallocationID" BackColor="White" BorderColor="#CCCCCC"
BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black"
GridLines="Horizontal" Width="100%">
<Columns>
<asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="ID" Visible="False">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("InternallocationID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("LocationName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Count" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblCount" runat="server" Text="totes"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
</asp:GridView>
</div>
</div>
<div class="dragbox" id="StorePayrollWidget" runat="server" visible="false">
<h2 style="font-size: 14pt">Store's Payroll</h2>
<div class="dragbox-content">
<asp:DropDownList ID="ddlPayrollStores" runat="server" OnSelectedIndexChanged="ddlPayrollStores_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
<asp:UpdatePanel ID="UpdatePanelPayroll" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlPayrollStores" EventName="SelectedIndexChanged"></asp:AsyncPostBackTrigger>
</Triggers>
<ContentTemplate>
<div class="dragbox-content">
<asp:Label ID="lblLabelOverTime" runat="server" Text="Total Overtime Hours: " Width="350px"></asp:Label>
<asp:Label ID="lblTotalOvertime" runat="server" Text=""></asp:Label>
<br />
<br />
<asp:Label ID="lblLabelHoliday" runat="server" Text="Total Holiday: " Width="350px"></asp:Label>
<asp:Label ID="lblTotalHoliday" runat="server" Text=""></asp:Label>
<br />
<br />
<asp:Label ID="lblLabelVacation" runat="server" Text="Total Vacation: " Width="350px"></asp:Label>
<asp:Label ID="lblTotalVacation" runat="server" Text=""></asp:Label>
<br />
<br />
<asp:Label ID="lbllableTotalHours" runat="server" Text="Total Hours: " Width="350px"></asp:Label>
<asp:Label ID="lblTotalStoreHours" runat="server" Text=""></asp:Label>
<br />
<br />
<asp:Label ID="lblLabelPay" runat="server" Text="Total Pay: " Width="350px"></asp:Label>
<asp:Label ID="lblTotalPay" runat="server" Text=""></asp:Label>
<br />
<br />
<div style="align-content: center">
<asp:LinkButton ID="lbDetailed" runat="server" Text="Detailed Report" PostBackUrl="~/Reporting/Payroll/StorePayroll.aspx"></asp:LinkButton>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
<div class="dragbox" id="ObjectiveWidget" runat="server" visible="false">
<h2 style="font-size: 14pt">Store Objectives-<asp:HyperLink ID="hlDaily" runat="server" NavigateUrl="~/Reporting/DailyReports/SalesByModel.aspx">Daily Report</asp:HyperLink></h2>
<div class="dragbox-content">
<asp:UpdatePanel ID="upObjective" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlNewUsed" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<div style="width: 100%">
<div style="text-align: center">
<asp:Label ID="lblObjNotice" runat="server" Text="Notice: If your dealership is in red; monthly objectives need updated!" Font-Bold="true" ForeColor="Red"></asp:Label>
<br />
<asp:DropDownList ID="ddlObjDealership" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlObjDealership_SelectedIndexChanged" Style="height: 22px">
</asp:DropDownList>
<asp:DropDownList ID="ddlNewUsed" runat="server" OnSelectedIndexChanged="ddlNewUsed_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem></asp:ListItem>
<asp:ListItem>New</asp:ListItem>
<asp:ListItem>Used</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlObjectiveMake" runat="server" Width="155px" OnSelectedIndexChanged="ddlObjectiveMake_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
</div>
<table style="display: inline-block; width: 45%">
<tr>
<td style="width: 100%">
<asp:Label ID="lblCommitObj" runat="server" Text="Commit OBJ: " Width="100%"></asp:Label><asp:TextBox ID="tbCommitObj" runat="server" Width="100%"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 100%">
<asp:Label ID="lblCommitGross" runat="server" Text="Commit Gross OBJECT: " Width="100%"></asp:Label><asp:TextBox ID="tbCommitGross" runat="server" Width="100%"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 100%">
<asp:Button ID="btnSubmitDaily" runat="server" Text="Submit" Height="32px" OnClick="btnSubmitDaily_Click" Width="68px" />
</td>
</tr>
<tr>
<td style="width: 100%">
<asp:Label ID="lblDailyMess" runat="server"></asp:Label>
</td>
</tr>
</table>
<table style="float: right; width: 45%" title="Current Monthly Objectives">
<caption>
<asp:Label ID="lblTitle" runat="server" Font-Bold="true" Font-Size="Small" Text="Current Monthly Objectives"></asp:Label></caption>
<tr>
<td style="text-align: center">
<br />
<asp:Label ID="lblObj" runat="server" Font-Bold="true" Text="Obj: "></asp:Label>
<br />
<br />
<br />
<asp:Label ID="lblCurrentObj" runat="server" Text=""></asp:Label>
</td>
<td style="text-align: center">
<br />
<asp:Label ID="lblGross" runat="server" Font-Bold="true" Text="Gross: "></asp:Label>
<br />
<br />
<br />
<asp:Label ID="lblCurrentGross" runat="server" Text=""></asp:Label>
</td>
</tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
</div>
I use this jQuery to drag and drop the widgets..
$(function () {
$('.dragbox')
.each(function () {
$(this).hover(function () {
$(this).find('h2').addClass('collapse');
}, function () {
$(this).find('h2').removeClass('collapse');
})
.find('h2').hover(function () {
$(this).find('.configure').css('visibility', 'visible');
}, function () {
$(this).find('.configure').css('visibility', 'hidden');
})
.click(function () {
$(this).siblings('.dragbox-content').toggle();
updateWidgetData();
})
.end()
.find('.configure').css('visibility', 'hidden');
});
$('.column').sortable({
connectWith: '.column',
handle: 'h2',
cursor: 'move',
placeholder: 'placeholder',
forcePlaceholderSize: true,
opacity: 0.4,
stop: function (event, ui) {
updateWidgetData();
}
})
.disableSelection();
});
My question is, how do I position the div's with the same id as the widgets name in document ready? For example, the div with the id CurrentDealsWidget is the first record in the table, with SortNo: 0, ColumnId: 1, Collapsed: 0, and UserId: 1. That means that this div needs to be in the div with the id "column1" and in the first position. I'm not very good with jQuery and javascript so I'm not sure how to go about this. Any help is greatly appreciated!
UPDATE: This is how I update the widget information..
jQuery
function updateWidgetData() {
var items = [];
$('.column').each(function () {
var columnId = $(this).attr('id');
$('.dragbox', this).each(function (i) {
var collapsed = 0;
if ($(this).find('.dragbox-content').css('display') == "none")
collapsed = 1;
//Create Item object for current panel
var item = {
id: $(this).attr('id'),
collapsed: collapsed,
order: i,
column: columnId
};
//Push item object into items array
items.push(item);
});
});
//Assign items array to sortorder JSON variable
var sortorder = { items: items };
$.ajax({
url: "/Handlers/SaveWidgets.ashx",
type: "POST",
contentType: "application/json; charset=uft-8",
dataType: "json",
data: JSON.stringify(sortorder),
success: function (response) {
$("#console").html('<div class="success">Dashboard Saved</div>').css('visibility', 'visible').fadeTo(600, 1);
setTimeout(function () {
$('#console').delay(500).fadeTo(600, 0);
}, 1000);
},
error: function (error) {
$("#console").html('<div class="fail">Dashboard was not saved!</div>').css('visibility', 'visible').fadeTo(600, 1);
setTimeout(function () {
$('#console').delay(500).fadeTo(600, 0);
}, 1000);
}
});
AND my Handler..
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboCao"].ConnectionString);
string userId;
public void ProcessRequest(HttpContext context)
{
string userName = context.User.Identity.Name;
conn.Open();
using (SqlCommand cmdUserId = new SqlCommand("SELECT UserId FROM tUser WHERE UserName = #UserName", conn))
{
cmdUserId.Parameters.AddWithValue("#UserName", userName);
userId = Convert.ToString(cmdUserId.ExecuteScalar());
System.Diagnostics.Debug.Write(userId);
}
String json = String.Empty;
// you have sent JSON to the server
// read it into a string via the input stream
using (StreamReader rd = new StreamReader(context.Request.InputStream))
{
json = rd.ReadToEnd();
}
// create an instance of YourDataModel from the
// json sent to this handler
SaveWidgetsDAL data = null;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(SaveWidgetsDAL));
using (MemoryStream ms = new MemoryStream())
{
byte[] utf8Bytes = Encoding.UTF8.GetBytes(json);
ms.Write(utf8Bytes, 0, utf8Bytes.Length);
ms.Position = 0;
data = serializer.ReadObject(ms) as SaveWidgetsDAL;
}
// update the DB and
// send back a JSON response
int rowsUpdated = 0;
foreach (var item in data.wdata)
{
string itemTitle = item.Title.Replace("FeaturedContent_", "");
string itemColumn = item.ColumnId.Replace("FeaturedContent_column", "");
using (SqlCommand cmd = new SqlCommand("UPDATE tWidgets SET Title = #Title, SortNo = #SortNo, ColumnId = #ColumnId, Collapsed = #Collapsed "
+ "WHERE UserId = #UserId AND Title = #Title;", conn))
{
cmd.Parameters.AddWithValue("#ColumnId", itemColumn);
cmd.Parameters.AddWithValue("#Title", itemTitle);
cmd.Parameters.AddWithValue("#SortNo", item.SortNo);
cmd.Parameters.AddWithValue("#Collapsed", item.Collapsed);
cmd.Parameters.AddWithValue("#UserId", userId);
rowsUpdated = cmd.ExecuteNonQuery();
}
}
conn.Close();
context.Response.ContentType = "application/json";
context.Response.Write("{ \"rows_updated\": " + rowsUpdated + " }");
}
public bool IsReusable
{
get
{
return false;
}
}
UPDATE 2:
With the solution below, I couldn't get it to work. Then I realized when I was updating the widget information, I had to remove FeaturedContent_column and FeaturedContent_ from the column and titles. So I figured I need to put them back in!
for (var i = 0; i < te.d.length; i++) {
$('#FeaturedContent_column' + te.d[i].ColumnId).append($('#FeaturedContent_' + te.d[i].Title));
if (te.d[i].Collapsed) {
//collapse
$('#' + te.d[i].Title).children('.dragbox-content').css('display') == "none";
}
}

This should do it:
for (var i = 0; i < te.d.length; i++) {
$('#column'+te.d[i].ColumnId).append($('#'+te.d[i].Title));
if (te.d[i].Collapsed)
{
//collapse
$('#'+te.d[i].Title).children(".dragbox-content').css('display') = "none";
}
}
This selects the correct column and appends the widget to it based upon the sorting of the array.
$('#column'+te.d[i].ColumnId): The generic $ function of jQuery allows us to select elements in the DOM through a wide range of selectors. Since your widgets have ids we use the id selector #. In this case we append the index to the string column to build the correct column selector.
Once the correct column is selected we're appending the widget to it by using .append and providing the element selected by $('#'+te.d[i].Title). This removes the element from its previous location and adds it to this column (div).

Related

Get selected checkbox and Ajax post save method for store data

i'm facing problem on how to get selected checkbox(single or multiple) and post back to method for save data from modal.
The function of checkbox javascript is working, so far no idea on how to put them in ajax and post.
Ajax still can't get the data of checkbox while checkbox is clicked!
Here is my modal gridview code for ASPX:
<div class="modal-dialog">
<div class="modal-body">
<asp:UpdatePanel ID="updateGV" runat="server">
<ContentTemplate>
<asp:Label CssClass="bolder" runat="server" ></asp:Label>
<input type="text" name="AddGroup" class="form-control" id="CreateGroup" onblur="GroupCheck()" />
<br /><br />
<asp:GridView runat="server" ID="gvLIST" CssClass="table table-bordered"
AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="gvCHECKALL" runat="server" onclick="allCHKBOX(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="gvCHECK" runat="server" onclick="singleCHKBOX(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" Visible="false">
<ItemTemplate>
<asp:Label ID="ID" runat ="server" Text='<%#Eval("ID") %>' style="display:none"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Name" DataField="NME"/>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<button id="btnROUPSAVE" runat="server" disabled="disabled" onclick="btnGroupSaveClick()" >
</div>
</div>
<script type="text/javascript">
function singleCHKBOX(chkBOX) {
var IsChecked = chkBOX.checked;
var Parent = document.getElementById('gvLIST');
var chkALL;
var items = Parent.getElementsByTagName('input');
var unchkALL = true;
for (i = 0; i < items.length; i++) {
if (items[i].id.indexOf('gvCHECKALL') != -1) {
chkALL = items[i];
continue;
}
if (items[i].type == "checkbox" && items[i].checked == false) {
unchkALL = false;
break;
}
}
chkALL.checked = unchkALL;
}
function allCHKBOX(spanChk) {
var IsChecked = spanChk.checked;
var cbxAll = spanChk;
var Parent = document.getElementById('gvLIST');
var items = Parent.getElementsByTagName('input');
for (i = 0; i < items.length; i++) {
if (items[i].id != cbxAll.id && items[i].type == "checkbox") {
items[i].checked = IsChecked;
}
}
}
</script>
function btnGroupSaveClick()
{
var CreateGroup = $("#CreateGroup").val().trim();
if (CreateGroup!= "" )
{
$.ajax({
type: "POST",
url: "test.aspx/CreateGroup",
data: "{'CreateGroup':'" + CreateGroup+ "', 'gvCHECK':'" + gvCHECK+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
}

Display error msg for from date and to date using javascript

I am posting the complete aspx code though i know that i should not post my complete code to show that this is my code i had posted the aspx code because in this we are using panel,ajax etc the main thing in this code is from date and to date which is in bold and italic i should not allow the user to enter from date greater than to date also i should not allow from date and to date not greater than todays date i need to display label messages to the user if from date is greater than to date and from date and to date should not be greater than todays date
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Home.aspx.cs" Inherits="Home1" %>
<%# Register Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" tagPrefix="ajax" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.dynDateTime.min.js" type="text/javascript"></script>
<script src="Scripts/calendar-en.min.js" type="text/javascript"></script>
<link href="Styles/calendar-blue.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
$("#<%= txtTAFromDate.ClientID %>").dynDateTime({
showsTime: true,
ifFormat: "%m/%d/%y %H:%M",
daFormat: "%l;%M %p, %e %m, %Y",
align: "BR",
electric: false,
singleClick: true,
displayArea: ".siblings('.dtcDisplayArea')",
button: ".next()"
});
$("#<%= txtTAToDate.ClientID %>").dynDateTime({
showsTime: true,
ifFormat: "%m/%d/%y %H:%M",
daFormat: "%l;%M %p, %e %m, %Y",
align: "BR",
electric: false,
singleClick: true,
displayArea: ".siblings('.dtcDisplayArea')",
button: ".next()"
});
});
</script>
<ajax:ToolkitScriptManager ID="scriptmanager1" runat="server">
</ajax:ToolkitScriptManager>
<div style="margin-left:10%;margin-top:03%;height:450px">
<ajax:TabContainer ID="TabContainer1" runat="server" CssClass="fancy fancy-green">
<ajax:TabPanel ID="tbpnluser" runat="server" >
<HeaderTemplate>Project wise details & Status </HeaderTemplate>
<ContentTemplate>
<asp:Panel ID="pnlPW" runat="server">
<h4><strong><center> Project wise details & Status </center></strong></h4>
<span>
Select ProjectName:<asp:DropDownList ID="ddlProject" runat="server" AutoPostBack="True" Width="183px" OnSelectedIndexChanged="ddlProject_SelectedIndexChanged"></asp:DropDownList>
</span>
(OR)<span>
Status:<asp:DropDownList ID="ddlStatus" runat="server" Visible="true" AutoPostBack="True" OnSelectedIndexChanged="ddlStatus_SelectedIndexChanged" >
</asp:DropDownList>
</span><span>
(OR) Domain:<asp:DropDownList ID="ddlDomain" runat="server" Visible="true" AutoPostBack="True" OnSelectedIndexChanged="ddlDomain_SelectedIndexChanged" ></asp:DropDownList>
</span>
<span style="float:right">
<asp:Button ID="Button1" runat="server" Text="Export" Visible="false"></asp:Button>
</span>
<div style="width:99%; height: 200px; overflow: auto">
<asp:GridView ID="grdPdetails" runat="server" EmptyDataText="No Records Available">
</asp:GridView>
</div>
</asp:Panel>
</ContentTemplate>
</ajax:TabPanel>
<ajax:TabPanel ID="tbpnlusrdetails" runat="server">
<HeaderTemplate>Team Activities</HeaderTemplate>
<ContentTemplate>
<asp:Panel ID="pnlAW" runat="server">
<h4><strong><center> Team Activities </center></strong></h4>
<div style="padding-left:100px">
<span>
ProjectName:<asp:DropDownList ID="ddlProjectNameTA" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlProjectNameTA_SelectedIndexChanged"></asp:DropDownList> <%----%>
</span>
<span>
(OR) UserName:<asp:DropDownList ID="ddlUsers" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlUsers_SelectedIndexChanged"></asp:DropDownList>
</span>
</div>
<br />
***<b><b><div style="padding-left:100px">
<span>
(OR) From Date<asp:TextBox ID="txtTAFromDate" Width="113px" runat="server" ReadOnly="true" ></asp:TextBox> <img src="calendar.png" />
</span>
<span>
To Date<asp:TextBox ID="txtTAToDate" Width="113px" runat="server" ReadOnly="true" ></asp:TextBox> <img src="calendar.png" />
<asp:Button ID="btnGet" runat="server" Text="GET" OnClick="btnGet_Click"/></b>***
</span>
</div></b> <asp:Label ID="lblErrmsgTA" runat="server" ForeColor="Red" Font-Bold="true"></asp:Label>
<div style="width:99%; height: 200px; overflow: auto">
<asp:GridView ID="gvTeamActiv" runat="server" EmptyDataText="No Records Available" >
</asp:GridView>
</div>
<asp:Button ID="Button3" runat="server" Text="Export" Visible="false"></asp:Button>
</asp:Panel>
</ContentTemplate>
</ajax:TabPanel>
</ajax:TabContainer>
</div>
</asp:Content>
What i have tried is
<asp:Button ID="btnGet" runat="server" OnClientClick="return compareDate()" Text="GET" OnClick="btnGet_Click" />
function compareDate() {
var from = document.getElementById('<%= txtTAFromDate.ClientID %>').value;
var to = document.getElementById('<%= txtTAToDate.ClientID %>').value;
// assuming the date is in dd/mm/yyyy format
from = toDateObject(from);
to = toDateObject(to);
if (from > to)
{
alert('start date should be lesser than end date');
return false;
}
return true;
}
function toDateObject(dateStr) {
var parts = dateStr.split('/');
var date = new Date(parts[2], (parts[1] - 1), parts[0]);
return date;
}
Here is a simple way to integrate what you want. This is all HTML and JavaScript, but shouldn't be too bad to implement. I have an error div where the errors appear. This can be styled however you want, but this should give you the idea.
function compareDate() {
var from = document.getElementById('fromDate').value;//use your asp id instead of 'fromDate'
var to = document.getElementById('toDate').value;//use your asp id instead of 'toDate'
// assuming the date is in mm/dd/yyyy format
from = toDateObject(from);
to = toDateObject(to);
var errors = document.getElementById('errors');
errors.innerHTML = "";
if (from > to)
{
errors.innerHTML += "start date should be lesser than end date<br>";
}
if (from > new Date () || to > new Date ()){
errors.innerHTML += "Dates must be in the past";
}
if(errors.innerHTML == ""){
return true;
}else{
return false;
}
}
function toDateObject(dateStr) {
var parts = dateStr.split('/');
var date = new Date(parts[2], (parts[0] - 1), parts[1]);
return date;
}
<div id="errors"></div>
<input type="text" id="fromDate" placeholder="fromDate (dd/mm/yyyy)">
<input type="text" id="toDate" placeholder="toDate (dd/mm/yyyy)">
<input type="button" onclick="compareDate()" value="submit">

Iterate Gridview to find greatest value using Javascript or jQuery

I have a gridview and scenario is: once someone deletes a row, it checks if NOTIF_RECIP_SEQ_NBR is maximum or not. If yes then it deletes that row else give a popup.
So basically once someone click on delete, it gets the NOtif_recip_Id of that row and iterates through Gridview to see if NOTIF_RECIP_SEQ_NBR of any row corresponding to that NOTIF_RECIP_ID is greater or not.
Question is It possible at client side? I did it with server side but I don't think that's a good way when I have all data on client side itself.
Please help. I tried multiple ways with Javascript but no use.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<script type="text/javascript">
function check(var a ,var b)
{
var grid = document.getElementById("GridView1");
var cellPivot;
debugger;
if (grid.rows.length > 0) {
for (i = 1; i < grid.rows.length-1; i++)
{
//here I want code to iterate and compare value.Is it possible?
alert("You must select an answer for all columns if Pivot is yes")
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
<table>
<tr>
<td>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label13" runat="server" Text="Notif_Recip Data" BackColor="Azure"></asp:Label>
<asp:GridView ID="GridView1" runat="server" DataKeyNames="NOTIF_RECIP_GUID" emptydatatext="There are no data records to display."
AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor="Beige"
HeaderStyle-BackColor = "AppWorkspace"
PageSize = "10" >
<Columns>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "NOTIF_RECIP_ID">
<ItemTemplate>
<asp:Label ID="lblNOTIF_RECIP_ID" runat="server"
Text='<%# Eval("NOTIF_RECIP_ID")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtNOTIF_RECIP_ID" runat="server"
Text='<%# Eval("NOTIF_RECIP_ID")%>'></asp:TextBox>
<asp:RequiredFieldValidator ID="v1txtNOTIF_RECIP_ID" runat="server" ControlToValidate="txtNOTIF_RECIP_ID" Text="?" ForeColor="Red" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText = "NOTIF_RECIP_SEQ_NBR">
<ItemTemplate>
<asp:Label ID="lblNOTIF_RECIP_SEQ_NBR" runat="server"
Text='<%# Eval("NOTIF_RECIP_SEQ_NBR")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server"
CommandArgument = '<%# Eval("NOTIF_RECIP_GUID")%>'
OnClientClick = "ValidateGrid"
Text = "Delete" OnClick = <%# "javascript:check('" + Eval("NOTIF_RECIP_SEQ_NBR")" + "Eval("NOTIF_RECIP_ID") + "')" %> ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
<HeaderStyle Font-Bold="True" />
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID = "GridView1" />
</Triggers>
</asp:UpdatePanel>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
I found the solution so pasting for anyone who in need.
<script type = "text/javascript">
function GetSelectedRow(lnk) {
debugger;
var table, tbody, i, rowLen, row, j, colLen, cell;
var result = confirm('Do you want to delete this value ?');
if (result) {
var x = document.getElementById('Label100');
table = document.getElementById("GridView1");
tbody = table.tBodies[0];
var bool = true;
var row = lnk.parentNode.parentNode;
var rowIndex = row.rowIndex - 1;
var RecipID = row.cells[0].innerText;
var Sqqno = parseInt(row.cells[1].innerText);
for (i = 1, rowLen = tbody.rows.length; i < rowLen; i++) {
row = tbody.rows[i];
var newrecipId = row.cells[0].innerText;
if (newrecipId == RecipID) {
cell = row.cells[1];
var newseq = parseInt(row.cells[1].innerText);
if (Sqqno < newseq) {
// debugger;
bool = false;
x = document.getElementById('Label100');
x.innerHTML = "ERROR-Delete RecipId with max Seqnumber";
x.style.display = "block";
return bool;
break;
}
}
else {
bool = true;
}
}
return bool;
}
else {
return false;
}
}
</script>

Check Box to be selected row index manner in gridview

I want to select the check box values in row index manner in a grid view, Can someone suggest how to select the checkbox? Please find below the code not working appropraitely.
function Check_Click(spanChk) {
{
var IsChecked = spanChk.checked;
var Chk = spanChk;
Parent = document.getElementById('Gv1');
var btn = document.getElementById('<%=btnsubmit.ClientID %>');
var items = Parent.getElementsByTagName('input');
var i = 0;
var tot = 0;
for (i = 0; i < items.length; i++) {
if (items[i].checked) {
tot = tot + 1;
if (tot > 2) {
alert('Cannot check more than 2 check boxes');
items[i].checked = false;
return;
}
}
}
}
}
This is my grid view file
<asp:GridView ID="Gv1" runat="server" AutoGenerateColumns="False" OnRowDataBound="Gv1_RowDataBound">
<Columns>
<asp:BoundField DataField="datedif" HeaderText="Day/Hour" SortExpression="datedif" />
<asp:TemplateField HeaderText="Hour1">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Enabled='<%# Eval("hour1").ToString().Equals("False") %>' OnCheckedChanged="CheckBox1_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour2">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" Enabled='<%# Eval("hour2").ToString().Equals("False") %>' OnCheckedChanged="CheckBox6_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour3">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox3" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox3" runat="server" Enabled='<%# Eval("hour3").ToString().Equals("False") %>' OnCheckedChanged="CheckBox3_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour4">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox4" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox4" runat="server" Enabled='<%# Eval("hour4").ToString().Equals("False") %>' OnCheckedChanged="CheckBox4_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour5">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox5" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox5" runat="server" Enabled='<%# Eval("hour5").ToString().Equals("False") %>' OnCheckedChanged="CheckBox5_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Call the JavaScript function from all of the CheckBoxes as shown below,
<asp:GridView ID="Gv1" runat="server" AutoGenerateColumns="False" OnRowDataBound="Gv1_RowDataBound">
<Columns>
<asp:BoundField DataField="datedif" HeaderText="Day/Hour" SortExpression="datedif" />
<asp:TemplateField HeaderText="Hour1">
<EditItemTemplate>
<asp:CheckBox ID="chkColumn1" runat="server" onclick="Check_Click(this)" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour1" runat="server" Enabled='<%# Eval("hour1").ToString().Equals("False") %>'
OnCheckedChanged="CheckBox1_CheckedChanged" onclick="Check_Click(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour2">
<EditItemTemplate>
<asp:CheckBox ID="ChkColumn2" runat="server" onclick="Check_Click(this)" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour2" runat="server" Enabled='<%# Eval("hour2").ToString().Equals("False") %>'
OnCheckedChanged="CheckBox6_CheckedChanged" onclick="Check_Click(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour3">
<EditItemTemplate>
<asp:CheckBox ID="chkColumn3" runat="server" onclick="Check_Click(this)" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour3" runat="server" Enabled='<%# Eval("hour3").ToString().Equals("False") %>'
OnCheckedChanged="CheckBox3_CheckedChanged" onclick="Check_Click(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour4">
<EditItemTemplate>
<asp:CheckBox ID="chkColumn4" runat="server" onclick="Check_Click(this)" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour4" runat="server" Enabled='<%# Eval("hour4").ToString().Equals("False") %>'
OnCheckedChanged="CheckBox4_CheckedChanged" onclick="Check_Click(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hour5">
<EditItemTemplate>
<asp:CheckBox ID="chkColumn5" runat="server" onclick="Check_Click(this)" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkHour5" runat="server" Enabled='<%# Eval("hour5").ToString().Equals("False") %>'
OnCheckedChanged="CheckBox5_CheckedChanged" onclick="Check_Click(this)" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And in the JavaScript, validate the selected CheckBox with its Row and then validate the number of items selected.
function IdExists(elements, id) {
for (var i = 0; i < elements.length; i++) {
if (elements[i].id.indexOf(id) > -1) {
return true;
}
}
return false;
}
function Check_Click(chkBx) {
Parent = document.getElementById('<% =Gv1.ClientID %>');
for (i = 0; i < Parent.rows.length; i++) {
var row = Parent.rows[i];
var items = row.getElementsByTagName('input');
if (items.length > 0) {
if (IdExists(items, chkBx.id)) {
var tot = 0;
for (j = 0; j < items.length; j++) {
if (items[j].type == 'checkbox' && items[j].checked) {
tot = tot + 1;
if (tot > 2) {
alert('Cannot check more than 2 check boxes');
chkBx.checked = false;
return;
}
}
}
}
}
}
}
You need to add a class name in the checkbox. then you can easily get all the checkbox by the class name.
function Check_Click(spanChk) {
{
var IsChecked = spanChk.checked;
var items = document.getElementsByClassName('myCheckBox');
var i = 0;
var tot = 0;
for (i = 0; i < items.length; i++) {
if (items[i].checked) {
tot = tot + 1;
if (tot > 2) {
alert('Cannot check more than 2 check boxes');
items[i].checked = false;
return;
}
}
}
}
}
UPDATE:
you can also use the below code to get all the checkbox.
var Checkboxes = document.querySelectorAll('input[type=checkbox]');

Insert data from grid view to sql server

I am doing project on asp.net. Right now I have got problem with insert data from gridview to sql server. In my gridview I have add a template as a textbox in order to input value. My problem is about insert value from textbox of gridview to sql server. My code as below:
<%# Page Title="" Language="C#" MasterPageFile="~/coca.Master" AutoEventWireup="true" CodeBehind="Orders.aspx.cs" Inherits="AssignmentWeb.Orders" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.SqlClient" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="center">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=txtQty]").val("0");
});
$("[id*=txtQty]").live("change", function () {
if (isNaN(parseInt($(this).val()))) {
$(this).val('0');
} else {
$(this).val(parseInt($(this).val()).toString());
}
});
$("[id*=txtQty]").live("keyup", function () {
if (!jQuery.trim($(this).val()) == '') {
if (!isNaN(parseFloat($(this).val()))) {
var row = $(this).closest("tr");
$("[id*=lblTotal]", row).html(parseFloat($(".price", row).html()) * parseFloat($(this).val()));
}
} else {
$(this).val('');
}
var grandTotal = 0;
$("[id*=lblTotal]").each(function () {
grandTotal = grandTotal + parseFloat($(this).html());
});
$("[id*=lblGrandTotal]").html(grandTotal.toString());
});
</script>
<br />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="ProductID" DataSourceID="SqlDataSource1" EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="ProductID" ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
<asp:BoundField DataField="AverageProduct" HeaderText="AverageProduct" SortExpression="AverageProduct" ItemStyle-CssClass="price"/>
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:TemplateField HeaderText="QtyOrder">
<ItemTemplate>
<asp:Textbox ID="txtQty" runat="server"></asp:Textbox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Grand Total:
<asp:Label ID="lblGrandTotal" runat="server" Text="0"></asp:Label>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:InventoryRouting %>" SelectCommand="SELECT [ProductName], [AverageProduct], [Description], [ProductID] FROM [Product]"></asp:SqlDataSource>
<br />
<asp:Button ID="btnOrder" runat="server" Text="Order!" Width="100px" OnClick="btnOrder_Click"/>
<br />
<br />
</div>
</asp:Content>
<script runat="server">
public void btnOrder_Click(object sender, EventArgs e)
{
int c = 0;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
SqlCommand cmd = new SqlCommand();
cmd.Connection = new SqlConnection("Data Source=LIDA-PC; Initial Catalog=InventoryRouting; Integrated Security=True");
//cmd.CommandText = "insert into orders values('" + Session["Username"].ToString() + "',#ProductID, #ProductName, #QtyOrder, #Total)";
cmd.CommandText = "insert into orders values('" + Session["Username"].ToString() + "',#ProductID , #ProductName, #QtyOrder, #Total)";
cmd.Connection .Open();
//cmd.Parameters.AddWithValue("'" + Session["Username"].ToString() + "'", GridView1.Rows[i].Cells[1].Text);
cmd.Parameters.AddWithValue("#ProductID", GridView1.Rows[i].Cells[0].Text);
cmd.Parameters.AddWithValue("#ProductName", GridView1.Rows[i].Cells[1].Text);
cmd.Parameters.AddWithValue("#QtyOrder", GridView1.Rows[i].Cells[4].Text);
cmd.Parameters.AddWithValue("#Total", GridView1.Rows[i].Cells[5].Text);
//InsertCommand = new SqlCommand("INSERT INTO [orders] ([client], [product], [amount], [price]) VALUES ('" + Session["Username"].ToString() + "', #ProductName, #AverageProduct, #QtyOrder, #Total)");
cmd.ExecuteNonQuery();
cmd.Connection.Close();
c = c + 1;
}
}
</script>
You need to convert grid view row cell control to the appropriate control explicitly.
access like this ((Textbox)(GridView1.Rows[i].Cells[4].Controls[0]).Text for your #QtyOrder
and ((Label)(GridView1.Rows[i].Cells[5].Controls[0]).Text for #Total.
OR
(GridView1.Rows[i].FindControl("txtQty") as TextBox).Text
Thanks.

Categories

Resources