What's wrong with my JavaScript? (C#/ASP.NET) - c#

Here is my JavaScript:
<script type="text/javascript">
function onholdev(index) {
var chk = document.getElementById('<%=grdCons.Rows[' + index + '].FindControl("chkHold").ClientID %>');
var txt = document.getElementById('<%=grdCons.Rows[' + index + '].FindControl("txtReason").ClientID %>');
if (chk.checked == true) {
txt.disabled = false;
}
else {
txt.disabled = true;
txt.value = "";
}
}
</script>
The 'index' variable comes from the RowDataBound event of my GridView, like so:
CheckBox chkHold = ((CheckBox)e.Row.FindControl("chkHold"));
chkHold.Attributes.Add("onchange", "onholdev(" + e.Row.RowIndex + ")");
However, I'm getting 'too many characters in string literal' in the first line of my function (beginning with var chk). Why is this?

You're mixing client and server-side script...you just can't do this. This is executed server-side:
grdCons.Rows[' + index + '].FindControl("chkHold").ClientID
But you're calling it client-side and trying to pass an ID, that's just not something you can do, look at your rendered JavaScript function and this will be much clearer. Instead just use the ID of the table, then you can find your controls that way, for example:
var row = document.getElementById("grdCons").rows[index];
var inputs = row.getElementsByTagName("input");
//then filter by ID match, class, whatever's easiest and set what you need here

That's probably because ASP.NET throws an error, which is written in the client side call of getElementById. The onholdev function is executed client - side, and so cannot pass the index parameter to ASP.NET which is executed server - side. Try this:
<script type="text/javascript">
function onholdev(checkbox, textbox) {
var chk = document.getElementById(checkbox);
var txt = document.getElementById(textbox);
if (chk.checked == true) {
txt.disabled = false;
}
else {
txt.disabled = true;
txt.value = "";
}
}
</script>
Replacing your server - side code with this:
CheckBox chkHold = ((CheckBox)e.Row.FindControl("chkHold"));
chkHold.Attributes.Add("onchange", "onholdev('" +
e.Row.FindControl("chkHold").ClientID + "','" +
e.Row.FindControl("txtReason").ClientID + "')");

The problem is your use of the single quote characters in ' + index + '. Change those to double qoutes and it should work.

Related

javascript function not being called

I have a dropdownlist and a fileupload control in a panel which is added with other controls in an UpdatePanel. When a value is selected from the dropdown and a file is uploaded, the Upload button is enabled. For this I have a javascript function as follows:
function SetUploadButtonEnabled(controlPanel, fileUploadId) {
var docTypesList = controlPanel.find("select");
var gotListVal = docTypesList.val() != "";
var fileUpload = $find(fileUploadId);
var gotFileVal = fileUpload.getUploadedFiles().length > 0;
var enable = gotListVal && gotFileVal;
if (enable) {
controlPanel.find(".GxButtonBlue").removeAttr("disabled");
}
else {
controlPanel.find(".GxButtonBlue").attr("disabled", true);
}
}
I am trying to call it from code behind as follows, but the function is not being called:
string script = "<script type=\"text/javascript\">"
+ "\n $(document).ready(function (){"
+ "\n $(document).on(\"change\", \"#" + this._DdDocumentTypes.ClientID + "\", function(event){"
+ "\n var docUploadControlPanel = $(this).closest(\"#" + this._DocUploadControlPanel.ClientID + "\");"
+ "\n SetUploadButtonEnabled(docUploadControlPanel, \"" + this._fiInput.ClientID + "\");"
+ "\n });"
+ "\n });"
+ "\n "
+ "</script>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "DocumentAjaxUploadCtrlScript_" + this.ClientID, script);
Since an Update Panel is there I even tried:
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "DocumentAjaxUploadCtrlScript_" + this.ClientID, script, true);
Please help me find why the function is never called!
Here's one way to do it. The key here is the pageComponents object.
ASPX or User Control
<script>
var pageComponents = {
documentTypeSelector: "#<%= _DdDocumentTypes.ClientID %>",
uploadControlSelector: "#<%= _DocUploadControlPanel.ClientID %>",
fiInputSelector: "#<%= _fiInput.ClientID %>"
};
</script>
JavaScript Place after the above
function SetUploadButtonEnabled(controlPanel, fileUploadId) {
var docTypesList = controlPanel.find("select");
var gotListVal = docTypesList.val() != "";
var fileUpload = $find(fileUploadId);
var gotFileVal = fileUpload.getUploadedFiles().length > 0;
var enable = gotListVal && gotFileVal;
if (enable) {
controlPanel.find(".GxButtonBlue").removeAttr("disabled");
}
else {
controlPanel.find(".GxButtonBlue").attr("disabled", true);
}
}
$(document).ready(function (){
$(document).on("change", pageComponents.documentTypeSelector, function(event){
var docUploadControlPanel = $(this).closest(pageComponents.uploadControlSelector);
SetUploadButtonEnabled(docUploadControlPanel, pageComponents.fiInputSelector);
});
});
Remarks
You can avoid using the "bee sting" syntax above by setting the control ClientIDMode property to Static (assuming you're using only ASP.NET Page, not a user control. Then your JavaScript would look like below:
$(document).ready(function (){
$(document).on("change", "#documentType", function(event){
var docUploadControlPanel = $(this).closest("#uploadControl");
SetUploadButtonEnabled(docUploadControlPanel, "#fiInput");
});
});
In addition the line:
var docUploadControlPanel = $(this).closest(pageComponents.uploadControlSelector);
could be written as:
var docUploadControlPanel = $(pageComponents.uploadControlSelector);
since ClientID always returns a unique element ID for the entire page.

AllowPaging after printing data in radGrid Telerik Asp.Net

I have been searching for a method to print data in radGrid Telerik and i found a way from Here As following:
Code Behind
radGrid.CurrentPageIndex = 0;
radGrid.ClientSettings.Scrolling.AllowScroll = false;
radGrid.AllowPaging = false;
radGrid.AllowFilteringByColumn = false;
radGrid.MasterTableView.GroupsDefaultExpanded = true;
radGrid.Rebind();
foreach (GridItem item in radGrid.MasterTableView.GetItems(new GridItemType[] { GridItemType.Pager, GridItemType.FilteringItem }))
item.Display = false;
RadAjaxPanel1.ResponseScripts.Add("PrintRadGrid('" + radGrid.ClientID + "')");
JavaScript:
function PrintRadGrid() {
var radGridE = $find('<%= radGrid.ClientID %>');
var previewWindow = window.open('about:blank', '', '', false);
var styleSheet = '<%= Telerik.Web.SkinRegistrar.GetWebResourceUrl(this.Page, radGrid.GetType(), String.Format("Telerik.Web.UI.Skins.{0}.Grid.{0}.css", radGrid.Skin)) %>';
var baseStyleSheet = '<%= Telerik.Web.SkinRegistrar.GetWebResourceUrl(this.Page, radGrid.GetType(), "Telerik.Web.UI.Skins.Grid.css") %>';
var htmlContent = "<html><head><link href = '" + styleSheet + "' rel='stylesheet' type='text/css'></link>";
htmlContent += "<link href = '" + baseStyleSheet + "' rel='stylesheet' type='text/css'></link></head>";
htmlContent = htmlContent + "<body>" + getOuterHTML(radGridE.get_element()) + "</body></html>";
previewWindow.document.open();
previewWindow.document.write(htmlContent);
previewWindow.document.close();
previewWindow.print();
if (!$telerik.isChrome) {
previewWindow.close();
}
}
The code is working well BUT it disables the Paging to print all pages. Now i want a way to Allow Paging again without refreshing the page.
How to set AllowPaging to true again without refresh the page?
Initiate a postback (preferably AJAX) after printing and enable paging in the code-behind. See how to initiate an ajaxRequest here: http://www.telerik.com/help/aspnet-ajax/ajax-client-side-api.html

asp.net gridview printing

i am printing a gridview in asp.net that is contained within a panel - it works in IE perfectly
In Opera 12.02 it appears to be printing out my main form not the print page ? Do you know why this is.
In Mozilla firefox 16.0.2 it only loads one page in the print preview and prints that one page? Do you know why this is?
I'm assuming the issue is in my javascript - i can post markup if needed but hopefully that will not be required.
thanks
Damo
javascript
<script type="text/javascript">
function PrintGridData(GridToPrint, PanelName) {
try {
var Grid = document.getElementById(GridToPrint);
var printContent = document.getElementById(PanelName);
//alert(printContent);
if (Grid) // See if the Grid Exists First
{
if (Grid.rows.length > 0) { // See if the Grid contains any rows
var windowUrl = 'about:blank';
var UserLoggedIn = $("#lblUser").text()
var now = new Date();
var strDateTime = [[AddZero(now.getDate()), AddZero(now.getMonth() + 1), now.getFullYear()].join("/"), [AddZero(now.getHours()), AddZero(now.getMinutes())].join(":"), now.getHours() >= 12 ? "PM" : "AM"].join(" ");
var Database = 'ProductionDatabase';
var windowName = 'Report';
var AuditPrintDetailEverypage = UserLoggedIn + ' Time : ' + strDateTime ;
var AuditPrintDetailLastPage = ' System Report ' + ' Source Database: ';
var WinPrint = window.open(windowUrl, windowName, 'left=300,top=300,right=500,bottom=500,width=1000,height=500');
WinPrint.document.write('<' + 'html' + '><head><link href="assets/css/Print.css" rel="stylesheet" type="text/css" /><title>' + AuditPrintDetailEverypage + '</title> </head><' + 'body style="background:none !important"' + '>');
WinPrint.document.write(printContent.innerHTML);
WinPrint.document.write(' ' + AuditPrintDetailLastPage);
WinPrint.document.write('<' + '/body' + '><' + '/html' + '>');
WinPrint.document.close();
//alert(printContent.innerHTML);
//alert(WinPrint.document);
if (window.opera) {
//alert('opera browser detected')
window.onload = window.print();
//window.onload = WinPrint.print();
//WinPrint.close();
}
else {
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
}
else { // No Results to print
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = 'You have no Results to print. Please run a report.';
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
}
}
else { // No Grid to print
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = 'You have no Grid to print. Please run a report.';
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
return;
}
}
catch (err) {
//alert(err);
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = err;
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
return;
}
}
function AddZero(num) {
try {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
catch (err) {
//alert(err);
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = err;
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
return;
}
}
</script>
window.onload = window.print(); should be window.onload = window.print;
Also my css had overflow: hidden; which opera and mozilla dont like so i removed these
now its working ok
thanks
damo

Any simple way of implementing highligh text results in gridview?

I used the search function and I've seen a lot of topics about "how to highlight a text " but I couldn't find a way to implement it in my asp.net website project.
I'm using a gridview and for search function I'm using this :
SqlDataSource1.SelectCommand = "select * from TableName where Name like '%" + TextBox1.Text + "%' or SecName like '%" + TextBox1.Text + "%'";
SqlDataSource1.DataBind();
How can I do it ? I would like someone to explain step by step , I need to do this for tomorrow and I'm not very advanced. ty
I think it could help you try it and add
$(document).ready(function () {
$('#txt_Search').keyup(function () {
searchTable($(this).val());
});
function searchTable(inputVal) {
var table = $('#GridView1');
table.find('tr').each(function (index, row) {
var allCells = $(row).find('td');
if (allCells.length > 0) {
var found = false;
allCells.each(
function (index, td) {
var regExp = new RegExp(inputVal, 'i');
if (regExp.test($(td).text())) {
found = true;
return false;
}});
if (found == true) $(row).addCss();
}
});
}
});

String from codebehind to array in Javascript

Hi all i have code that reads from a DB and populates a string in the code behind
List<string> rows = new List<string>();
DataTable prods = common.GetDataTable("vStoreProduct", new string[] { "stpt_Name" }, "stpt_CompanyId = " + company.CompanyId.ToString() + " AND stpt_Deleted is null");
foreach (DataRow row in prods.Rows)
{
prodNames += "\"" + row["stpt_Name"].ToString().Trim() + "\",";
}
string cleanedNanes = prodNames.Substring(0, prodNames.Length - 1);
prodNames = "[" + cleanedNanes + "]";
This produces something like ["Test1","Test2"]
In javascript i have
var availableTags = '<% =prodNames %>';
alert(availableTags);
How can i access this like an array in javascript like
alert(availableTags[5]);
and get the full item at the given index.
Thanks any help would be great
Get rid of the quotes:
var availableTags = <% =prodNames %>;
With the quotes there, you're creating a JavaScript string. Without them, you've got a JavaScript array constant.
You're going to have to split the variable from .NET into a JS array.
Check out: http://www.w3schools.com/jsref/jsref_split.asp
Example based on your code:
var availableTags = '<% =prodNames %>';
var mySplitResult = availableTags .split(",");
alert(mySplitResult[1]);
I believe split() will do what you want:
var availableTagsResult = availableTags.split(",");
alert(availableTagsResult[1]) //Display element 1
This will create an array from the string which has been split on ,

Categories