Not able to maintain checkbox during pagination using jQuery - asp.net

I have 4 buttons for pagination(first,move next,move back and last).
I am trying to maintain checkbox during pagination. The problem is that
when I select any checkbox and then go to next page and then come back to the same page, it doesn't show previously checked checkbox, but as soon as click on next page, before going to next page it shows value checked.
Here is my code, can anyone guide me where I am doing wrong?
$(function() {
toggleSelectBtnOnCheck();
});
function toggleSelectBtnOnCheck() {
debugger;
//Register checkbox click handler to be called when Ajax requests complete.
$('#contentDiv').ajaxComplete(function() {
$('.tdHeadForCheckboxRadioButton').append('<input class="search" onclick="checkUnchekAllCheckboxes(this);" type="checkbox"/>');
$('.afirst, .aprev, .anext, .alast, .search:checkbox').click(function() {
var selectedVal = $(this).closest('td');
var selectClaim = selectedVal.next().text();
var selectSuffix = selectedVal.next().next().text();
var ClaimSuffix = selectClaim + '|' + selectSuffix + ',';
if ($(this).is(':checked')) {
document.getElementById('hdnChkClaim').value += ClaimSuffix;
} else if ($('#hdnChkClaim').val().indexOf(ClaimSuffix) != -1) {
$('#hdnChkClaim').val($('#hdnChkClaim').val().replace(ClaimSuffix, ''));
}
alert($('#hdnChkClaim').val());
if (jQuery(this).attr("href") != "") {
//button.disable($('span.btnSelect'));
var SelectedItemsCheckboxID = [];
if ($('#hdnChkClaim').val() != '') {
debugger;
if (ClaimSuffix.indexOf(',') != -1) {
ClaimSuffix = ClaimSuffix.substr(0, ClaimSuffix.length - 1); //remove last ','
}
SelectedItemsCheckboxID = $('#hdnChkClaim').val().split(',');
for (i = 0; i < SelectedItemsCheckboxID.length; i++) {
var claimDetails = SelectedItemsCheckboxID[i].split('|');
a = claimDetails[0];
b = claimDetails[1];
$('tr').filter(function(index) {
var columns = $(this).children('td');
alert(columns.eq(1).text() === a && columns.eq(2).text() === b);
return columns.eq(1).text() === a && columns.eq(2).text() === b;
}).find('input:checkbox').attr("checked", true);
;
}
}
if ($('.search:checkbox:checked').length > 0) {
button.enable($('span.btnSelect'));
} else {
button.disable($('span.btnSelect'));
}
}
});
});
}

You have to use the hidden field , when user select a checkbox , add it to hidden field like comma separated Ids , when every page is moved because of pagination check if any of the id in the current page is belong to the hidden field if yes mark them to checked.

Related

Using multi filter datatables in asp.net MVC

I'm trying to implement the multiple filters in the datatables in asp.net, but the time I search a value, my table is not updated.
I followed the official example of the site, but it did not work. Here is the source code I'm using.
JS on VIEW
$('#students tfoot th').each( function () {
var title = $(this).text();
if (title !== "") {
$(this).html('<input type="text" class="form-control form-control-sm" style="width: 100%" placeholder="' + title + '" />');
} else {
$(this).html('<div class="text-center">-</div>');
}
} );
tabela.columns().every( function () {
var that = this;
$( 'input', this.header() ).on( 'keydown', function (ev) {
if (ev.keyCode == 13) { //only on enter keypress (code 13)
that
.search( this.value )
.draw();
}
} );
} );
ACTION on CONTROLLER
[HttpPost]
public JsonResult Listar2()
{
var search = Request.Form.GetValues("search[value]")?[0];
var list = db.Students;
if (!string.IsNullOrEmpty(search))
{
list = list.Where(m => m.name.ToLower().Contains(search.ToLower()) || m.class.ToLower().Contains(search.ToLower()));
}
var draw = Request.Form.GetValues("draw")?[0];
var start = Request.Form.GetValues("start")?[0];
var length = Request.Form.GetValues("length")?[0];
var width = length != null ? Convert.ToInt32(length) : 0;
var skip = start != null ? Convert.ToInt32(start) : 0;
var totalRecords = list.Count();
var resultFinal = list.Skip(skip).Take(width).ToList();
return Json(new
{
data = resultFinal,
draw,
recordsFiltered = totalRecords,
recordsTotal = totalRecords
});
}
I don't know what you want to accomplish. The official example uses JavaScript to sort the datatable which is inserted into HTML already. You should load all the entries first, pass them to the view and then this script should filter those entries

Bootstrap validation without form tag in asp.net for particular button

In single page for two different buttons, Bootstrap validation without form tag in asp.net for particular buttons. Similar to like validation group.. Is there any way?
I think you have to do a trick for this...
1) Identify the classes that is applied on validate
2) Write a script to validate on click event for particular button
your script will be like
$("#btnId").click(function(){
var IsValid=true;
if($("#txtName").val()=="")
{
IsValid=false;
//Apply the classes that you have identified
$("#txtName").attr("class","className");
}
else
{
//Apply normal class
$("#txtName").attr("class","className");
}
if(IsValid)
{
return True;
}
else
{
return False;
}
});
this is only idea so don't look out the syntax.....
may this help
use customize jQuery on each button's Click
$('.login').on('click', LoginFunction);
$('.register').on('click', RegisterFunction);
function LoginFunction() {
var valid = true,
errorMessage = "";
if ($('#Login').val() == '') {
errorMessage = "please enter your Login \n";
valid = false;
}
if ($('#Password').val() == '') {
errorMessage += "please enter your PAssword\n";
valid = false;
}
if( !valid && errorMessage.length > 0){
alert(errorMessage);
}
}
function RegisterFunction() {
var valid = true,
errorMessage = "";
if ($('#name').val() == '') {
errorMessage = "please enter your name \n";
valid = false;
}
if ($('#address').val() == '') {
errorMessage += "please enter your address\n";
valid = false;
}
if ($('#email').val() == '') {
errorMessage += "please enter your email\n";
valid = false;
}
if( !valid && errorMessage.length > 0){
alert(errorMessage);
}
}

Resize iframe - do have access to external url code

I have seen lots of questions about resizing iframes but all of those do not have access to the external url. In this case I do. I can insert a script into the head tag. I was trying to use this script inserted into the main page header containing the iframe (i know the opening and closing frame tags are wrong - it would not let me leave them in:
iframe id="frame-one" scrolling="no" frameborder="0" src="yoursitehereexample" onload="FrameManager.registerFrame(this)" /iframe
and this the js in the header (linked FrameManager.js file)
var FrameManager =
{
currentFrameId : '',
currentFrameHeight : 0,
lastFrameId : '',
lastFrameHeight : 0,
resizeTimerId : null,
init : function()
{
if (FrameManager.resizeTimerId == null)
{
FrameManager.resizeTimerId = window.setInterval(FrameManager.resizeFrames, 500);
}
},
resizeFrames : function()
{
FrameManager.retrieveFrameIdAndHeight();
if ((FrameManager.currentFrameId != FrameManager.lastFrameId) ||
(FrameManager.currentFrameHeight != FrameManager.lastFrameHeight))
{
var iframe = document.getElementById(FrameManager.currentFrameId.toString());
if (iframe == null) return;
iframe.style.height = FrameManager.currentFrameHeight.toString() + "px";
FrameManager.lastFrameId = FrameManager.currentFrameId;
FrameManager.lastFrameHeight = FrameManager.currentFrameHeight;
window.location.hash = '';
}
},
retrieveFrameIdAndHeight : function()
{
if (window.location.hash.length == 0) return;
var hashValue = window.location.hash.substring(1);
if ((hashValue == null) || (hashValue.length == 0)) return;
var pairs = hashValue.split('&');
if ((pairs != null) && (pairs.length > 0))
{
for(var i = 0; i < pairs.length; i++)
{
var pair = pairs[i].split('=');
if ((pair != null) && (pair.length > 0))
{
if (pair[0] == 'frameId')
{
if ((pair[1] != null) && (pair[1].length > 0))
{
FrameManager.currentFrameId = pair[1];
}
}
else if (pair[0] == 'height')
{
var height = parseInt(pair[1]);
if (!isNaN(height))
{
FrameManager.currentFrameHeight = height;
FrameManager.currentFrameHeight += 15;
}
}
}
}
}
},
registerFrame : function(frame)
{
var currentLocation = location.href;
var hashIndex = currentLocation.indexOf('#');
if (hashIndex > -1)
{
currentLocation = currentLocation.substring(0, hashIndex);
}
frame.contentWindow.location = frame.src + '?frameId=' + frame.id + '#' + currentLocation;
}
};
window.setTimeout(FrameManager.init, 300);
Then...I put this in the framed page header ResizeFrame.js as a link:
//orig frame mgr script
$.getScript("http://www.yoursitehereexamle.com/js/FrameManager.js", function(){
});
// external heights load
function publishHeight()
{
if (window.location.hash.length == 0) return;
var frameId = getFrameId();
if (frameId == '') return;
var actualHeight = getBodyHeight();
var currentHeight = getViewPortHeight();
if (Math.abs(actualHeight - currentHeight) > 15)
{
var hostUrl = window.location.hash.substring(1);
hostUrl += "#";
hostUrl += 'frameId=' + frameId;
hostUrl += '&';
hostUrl += 'height=' + actualHeight.toString();
window.top.location = hostUrl;
}
}
function getFrameId()
{
var qs = parseQueryString(window.location.href);
var frameId = qs["frameId"];
var hashIndex = frameId.indexOf('#');
if (hashIndex > -1)
{
frameId = frameId.substring(0, hashIndex);
}
return frameId;
}
function getBodyHeight()
{
var height;
var scrollHeight;
var offsetHeight;
if (document.height)
{
height = document.height;
}
else if (document.body)
{
if (document.body.scrollHeight)
{
height = scrollHeight = document.body.scrollHeight;
}
if (document.body.offsetHeight)
{
height = offsetHeight = document.body.offsetHeight;
}
if (scrollHeight && offsetHeight)
{
height = Math.max(scrollHeight, offsetHeight);
}
}
return height;
}
function getViewPortHeight()
{
var height = 0;
if (window.innerHeight)
{
height = window.innerHeight - 18;
}
else if ((document.documentElement) && (document.documentElement.clientHeight))
{
height = document.documentElement.clientHeight;
}
else if ((document.body) && (document.body.clientHeight))
{
height = document.body.clientHeight;
}
return height;
}
function parseQueryString(url)
{
url = new String(url);
var queryStringValues = new Object();
var querystring = url.substring((url.indexOf('?') + 1), url.length);
var querystringSplit = querystring.split('&');
for (i = 0; i < querystringSplit.length; i++)
{
var pair = querystringSplit[i].split('=');
var name = pair[0];
var value = pair[1];
queryStringValues[name] = value;
}
return queryStringValues;
}
// window load
window.onload = function(event)
{
window.setInterval(publishHeight, 300);
}
But no luck on getting it to work - can anyone see where I went wrong. The iframe still appears but does not scale. Many Thanks!
Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.
local (iframe) page: just insert a code snippet
remote (external) page: you need a "body onload" and a "div" that holds all contents. And body needs to be styled to "margin:0"
Local:
<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>
<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>
You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).
Remote:
You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).
<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>
So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.
The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".
Hope this helps. Sorry for my english.

accessing checkboxlist text through javascript

I have a checkbox list i have which i have bound some document name to it's text field.now i need to find only the checkboxes which the text contains the .pdf extension and check them all in a single checkbox click.i have written the following javascript but it doesn't work for me
function CheckAllPDF() {
var checkBoxList = document.getElementById("<%= cblFiles.ClientID %>");
var checkBoxes = checkBoxList.getElementsByTagName("input");
for (i = 0; i < checkBoxes.length; i++) {
var string = checkBoxes[i].parentNode.getElementsByTagName('label').innerHTML;
var match = string.indexOf(".pdf");
if (match != -1) {
checkBoxes[i].checked = true;
}
else {
checkBoxes[i].checked = false;
}
}
can some one help?
When you put an asp.net check box list in the page it is translated to a list of input of type checkbox so you need to access each control and check it so you javascript code should look like:
//Get the main id of the asp.net check box list
var checkboxId = '<%= CheckBoxList1.ClientID %>';
//Loop on all generated input check boxes where the count function determine the number of generated checkboxes
for (var i = 0; i < <%= Count() %>; i++) {
//Append the count on the main asp.net check box id the value ('_'+i)
var checkBox = document.getElementById(checkboxId + '_' + i);
var checkBoxValue = checkBox.value;
var match = checkBoxValue.indexOf(".pdf");
if (match != -1) {
checkBox.checked = true;
}
else {
checkBox.checked = false;
}
}
And in your code behind write the count function as follows:
public int Count()
{
return CheckBoxList1.Items.Count;
}

Auto save of form

I have form in ASP.NET 3.5. Where lot of data elements and where i have Save and Submit buttions. I need to auto save my form every 2 min. What is the best way to implement this kind of functionility in ASP.NET.
I struggled for awhile with the same problem. The trouble was that I didn't want to save into the usual database tables because that would've required validation (validating integers, currencies, dates, etc). And I didn't want to nag the user about that when they may be trying to leave.
What I finally came up with was a table called AjaxSavedData and making Ajax calls to populate it. AjaxSavedData is a permanent table in the database, but the data it contains tends to be temporary. In other words, it'll store the user's data temporarily until they actually complete the page and move onto the next one.
The table is composed of just a few columns:
AjaxSavedDataID - int:
Primary key.
UserID - int:
Identify the user (easy enough).
PageName - varchar(100):
Necessary if you're working with multiple pages.
ControlID - varchar(100):
I call this a ControlID, but it's really just the ClientID property that .NET exposes for all of the WebControls. So if for example txtEmail was inside a user control named Contact then the ClientID would be Contact_txtEmail.
Value - varchar(MAX):
The value the user entered for a given field or control.
DateChanged - datetime:
The date the value was added or modified.
Along with some custom controls, this system makes it easy for all of this to "just work." On our site, the ClientID of each textbox, dropdownlist, radiobuttonlist, etc is guaranteed to be unique and consistent for a given page. So I was able to write all of this so that the retrieval of the saved data works automatically. In other words, I don't have to wire-up this functionality every time I add some fields to a form.
This auto-saving functionality will be making its way into a very dynamic online business insurance application at techinsurance.com to make it a little more user friendly.
In case you're interested, here's the Javascript that allows auto-saving:
function getNewHTTPObject() {
var xmlhttp;
/** Special IE only code */
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end
#*/
/** Every other browser on the planet */
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
}
catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
function AjaxSend(url, myfunction) {
var xmlHttp = getNewHTTPObject();
url = url + "&_did=" + Date();
xmlHttp.open("GET", url, true);
var requestTimer = setTimeout(function() { xmlHttp.abort(); }, 2000);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState != 4)
return;
var result = xmlHttp.responseText;
myfunction(result);
};
xmlHttp.send(null);
}
// Autosave functions
var SaveQueue = []; // contains id's to the DOM object where the value can be found
var SaveQueueID = []; // contains id's for binding references (not always the same)
function ArrayContains(arr, value) {
for (i = 0; i < arr.length; i++) {
if (arr[i] == value)
return true;
}
return false;
}
function GetShortTime() {
var a_p = "";
var d = new Date();
var curr_hour = d.getHours();
if (curr_hour < 12)
a_p = "AM";
else
a_p = "PM";
if (curr_hour == 0)
curr_hour = 12;
else if (curr_hour > 12)
curr_hour = curr_hour - 12;
var curr_min = d.getMinutes();
curr_min = curr_min + "";
if (curr_min.length == 1)
curr_min = "0" + curr_min;
return curr_hour + ":" + curr_min + " " + a_p;
}
function Saved(result) {
if (result == "OK") {
document.getElementById("divAutoSaved").innerHTML = "Application auto-saved at " + GetShortTime();
document.getElementById("divAutoSaved").style.display = "";
}
else {
document.getElementById("divAutoSaved").innerHTML = result;
document.getElementById("divAutoSaved").style.display = "";
}
}
function getQueryString(name, defaultValue) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == name) {
return pair[1];
}
}
return defaultValue;
}
function urlencode(str) {
return escape(str).replace(/\+/g, '%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/#/g, '%40');
}
function AutoSave() {
if (SaveQueue.length > 0) {
var url = "/AjaxAutoSave.aspx?step=" + getQueryString("step", "ContactInformation");
for (i = 0; i < SaveQueue.length; i++) {
switch (document.getElementById(SaveQueue[i]).type) {
case "radio":
if (document.getElementById(SaveQueue[i]).checked)
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
break;
case "checkbox":
if (document.getElementById(SaveQueue[i]).checked)
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
default:
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
}
}
SaveQueue = [];
SaveQueueID = [];
AjaxSend(url, Saved);
}
}
function AddToQueue(elem, id) {
if (id == null || id.length == 0)
id = elem.id;
if (!ArrayContains(SaveQueueID, id)) {
SaveQueue[SaveQueue.length] = elem.id;
SaveQueueID[SaveQueueID.length] = id;
}
}
Add this to your page to make this work:
window.setInterval("AutoSave()", 5000);
And to apply this to a Textbox, DropdownList, Listbox, or Checkbox you just need to add this attribute:
onchange="AddToQueue(this)"
...or this for a RadioButtonList or CheckBoxList:
onchange="AddToQueue(this, '" + this.ClientID + "')"
I'm sure this Javascript could be simplified quite a bit if you used JQuery so you might want to consider that. But in any case, AJAX is the thing to use. It's what Google uses to auto-save your email message in gmail, and the same thing is in blogger when you're writing a new post. So I took that concept and applied it to a huge ASP.NET application with hundreds of form elements and it all works beautifully.
Use the Timer class and the Tick method.

Resources