accessing checkboxlist text through javascript - asp.net

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

Related

Calling a javascript select change from c#

I have javascript function when a control value is changed i am firing a javascript now i wanted to do from c# code.When a value to a control is assigned i wanted it to fire the javascript .Please Help !!.
function AddSelectedUser(sender, eventArgs) {
var dataItem = eventArgs.get_DataItem();
if (dataItem != null) {
// get the selected values
var subscribedUserId = parseInt(eventArgs.get_Value());
var subscribedUserText = eventArgs.get_Text();
var recipientType = dataItem.get_attributes().getAttribute("RecipientType");
//Check if the selected user or group already exists in the selected list
var isExisting = false;
var JSONString = $get(hdnSelectedUsersJsonId).value;
var selectedUserColl = new Array();
if (JSONString != "") {
selectedUserColl = Sys.Serialization.JavaScriptSerializer.deserialize(JSONString);
}
for (j = 0; j < selectedUserColl.length; j++) {
if (selectedUserColl[j].DisplayID == subscribedUserId && selectedUserColl[j].RecipientType == recipientType) {
isExisting = true;
break;
}
}
if (isExisting == false) {
//Add the selected user or group.
var emptyRecipient = new Object();
emptyRecipient.DisplayID = subscribedUserId;
emptyRecipient.DisplayName = subscribedUserText;
emptyRecipient.RecipientType = recipientType;
selectedUserColl.push(emptyRecipient);
$get(hdnSelectedUsersJsonId).value = Sys.Serialization.JavaScriptSerializer.serialize(selectedUserColl);
ConstructTable(false);
}
sender.resetData();
var divScroll = $get('selectedUsersDiv');
divScroll.scrollTop = divScroll.scrollHeight;
}
}
<tele:autocomplete runat="server" pickervisible="false" id="SubscribedUsers" height="100px"
width="250px" dropdownwidth="248px" cssclass="susbscribedUser" pickertooltip="Select Users or Notification Groups"
providertype="InstantNotificationUsersProvider" matchingtype="Contains" controlbehavior="RestrictedToDropdown"
onclientsidecomponentchanged="AddSelectedUser" AutoPostBack="true" />
If you just want to call this function from c# then use ScriptManager.RegisterStartupScript() method.
It's easy just read this method properly and call you function.

Iterate through the model object in javascript (foreach and <text>)

As going through the site i got how to access the model in javascript and how to loop it in javascript.
i am using text tag to access the item in a model. when i use i am not able to add break.
#foreach (var item in Model.ArrayDetails)
{
var checklower = false;
var checkUpper = false;
var loopentered = false;
<text>
if(#item.Id ==1)
{
if(#item.LowerBound <= obj.value)
{
loopentered=true;
checklower=true;
}
if(loopentered)
{
alert(#item.UpperBound <= obj.value);
if(#item.UpperBound <= obj.value)
{
checkUpper = true;
}
}
if(checkUpper && checklower)
{
***// here i want to add break statement(if i add javascript wont work)***
}
}
</text>
}
Can some one suggest me how can solve this.
Don't write this soup. JSON serialize your model into a javascript variable and use this javascript variable to write your javascript code. Right now you have a terrible mixture of server side and client side code.
Here's what I mean in practice:
<script type="text/javascript">
// Here we serialize the Model.ArrayDetails into a javascript array
var items = #Html.Raw(Json.Encode(Model.ArrayDetails));
// This here is PURE javascript, it could (AND IT SHOULD) go into
// a separate javascript file containing this logic to which you could
// simply pass the items variable
for (var i = 0; i < items.length; i++) {
var item = items[i];
var checklower = false;
var checkUpper = false;
var loopentered = false;
if (item.Id == 1) {
if (item.LowerBound <= obj.value) {
loopentered = true;
checklower = true;
}
if (loopentered) {
alert(item.UpperBound <= obj.value);
if(item.UpperBound <= obj.value) {
checkUpper = true;
}
}
if (checkUpper && checklower) {
break;
}
}
}
</script>
and after moving the javascript into a separate file your view will simply become:
<script type="text/javascript">
// Here we serialize the Model.ArrayDetails into a javascript array
var items = #Html.Raw(Json.Encode(Model.ArrayDetails));
myFunctionDefinedIntoASeparateJavaScriptFile(items);
</script>

Not able to maintain checkbox during pagination using jQuery

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.

runtime generated Checkbox validation

I have panel in the asp.net webpage, and i m generating the checkbox at runtime..
i want to validate checkbox, required field validator when form submit.
here is my code:
cv = new CustomValidator();
cv.ID = "cv" + "_" + dt.Rows[0]["RefQueID"].ToString();
cv.ValidationGroup = "grp";
cv.Display = ValidatorDisplay.None;
cv.ErrorMessage = "- Question " + intQuestionNo.ToString();
cv.ClientValidationFunction = "chkCount";
cv.Attributes.Add("rfvid", cv.ID.ToString());
//this portion of code is for custom validation javascript function
StringBuilder sb = new StringBuilder();
sb.Append("<script type='text/javascript'> function chkCount(sender,args) { ");
sb.Append(" args.IsValid = GetChk(document.getElementById('ctl00_ContentPlaceHolder1_" + cbl.ID.ToString() + "'))");
sb.Append(" } </script>");
Page page = HttpContext.Current.Handler as Page;
page.RegisterStartupScript("_Check", sb.ToString());
and in my javascript function i return this:
function GetChk(chkbox, args) {
if (!isConfirmed) {
alert('hi');
var chkBoxList = document.getElementById(chkbox.ClientID);
var chkBoxCount = chkBoxList.getElementsByTagName("input");
for (var i = 0; i < chkBoxCount.length; i++) {
if (chkBoxCount[i].checked == true) {
return true;
}
}
return false;
}
return true;
}
but i m not getting the value of the checkbox...
required value:=
ctl00_ContentPlaceHolder1_tc_hospital_improvement_features_tp_Reflection_cbl_116_0
Actual Value:=
ctl00_ContentPlaceHolder1_tc_hospital_improvement_features_tp_complete_stage_chk_confirm
pls help...
first get the runtime generated control into the codebehind file from class file.
and then secondly after getting the control property, we can validate the checbox list.
Get the control into codebehind file from class file.
CheckBoxList cbl = (CheckBoxList)pnlref.FindControl("cbl_116");
provide the javascript validation to the runtime generated checkbox list.
function GetChk(chkbox, args) {
if (!isConfirmed) {
var chkBoxList = document.getElementById('ctl00_ContentPlaceHolder1_tc_hospital_improvement_features_tp_Reflection_cbl_116');
var chkBoxCount = chkBoxList.getElementsByTagName("input");
for (var i = 0; i < chkBoxCount.length; i++) {
if (chkBoxCount[i].checked == true) {
return true;
}
}
return false;
}
return true;
}

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