I'm creating a print function and the key is to call the grid that I want to print. It has been working well if the grid is existing on the aspx page, until when I also need to print a list of RadGrids that are generated programmatically behind the code then JavaScript cannot detect these non-existing grids and return the error of "the control does not exist". Just to be clear, it's not working because at the time when I'm typing the code, there's no RadGrid_Dynamic on the page, hence erroring. There's nothing to do with when the page execute/page life cycle etc.
My work around is to try to call the control by string value, as using
$find('<%= RadGrid_Dynamic.ClientID %>'),
the page will highlight RadGrid_Dynamic and say it doesn't exists as mentioned above. Below is my code, I've also tried replacing the $find() with document.getElementById(), but no luck, any advice? Thanks.
function getOuterHTML(obj) {
if (typeof (obj.outerHTML) == "undefined") {
var divWrapper = document.createElement("div");
var copyOb = obj.cloneNode(true);
divWrapper.appendChild(copyOb);
return divWrapper.innerHTML
}
else {
return obj.outerHTML;
}
}
function Print() {
var previewWindow = window.open('about:blank', '', '', false);
var styleSheet = '<%= Telerik.Web.SkinRegistrar.GetWebResourceUrl(this, RadGrid1.GetType(), String.Format("Telerik.Web.UI.Skins.{0}.Grid.{0}.css", RadGrid1.Skin)) %>';
var baseStyleSheet = '<%= Telerik.Web.SkinRegistrar.GetWebResourceUrl(this, RadGrid1.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><body>";
for (i = 1; i < 13; i++) {
var CYGrid = "RadGrid_CY_Strategy_" + String(i);
var CYradGrid = $find('<%=CYGrid.ClientID %>'); //Highlighted as red and erorr: The Name 'CYGird' does not exist in the current content
var LYGrid = "RadGrid_LY_" + String(i);
var LYradGrid = $find('<%=LYGrid.ClientID %>'); //Ditto
htmlContent += getOuterHTML(CYradGrid.get_element());
if (LYradGrid.hidden == false) {
htmlContent += getOuterHTML(LYradGrid.get_element());
}
}
htmlContent += "</body></html>";
previewWindow.document.open();
previewWindow.document.write(htmlContent);
previewWindow.document.close();
previewWindow.print();
if (!$telerik.isChrome) {
previewWindow.close();
}
}
You could programmatically assign an ID to the dynamic grid when it's being created and use that ID to do a $find().
Related
I have this basic code for the development of what I need, who can help me is a lot of help for me !!
note: I used the function .search () and replace () without getting good results, I do not know what else way to take
var fjstr = document.getElementsByClassName("js-product-variants-list");
var fjinnerColor = '';
var fjscolor2 = ["Rojo-Wengue",
"Aqua-Natural",
"Gris/Decape",
"Rosa-Blanco",
"Turqueza-Wengue",
"Turqueza-Blanco",
"Naranja-Natural",
"Amarillo-Natural"];
var resultado = "";
var pos = -1
fjscolor2.forEach(function(element) {
pos = fjstr.innerHTML.search(element.toString());
if(pos!=-1){
resultado += "<a href='#" + (fjscolor[i]) + "' ><li class='fj-product-color-icon' id='color-" + (fjscolor[i]) + "'></li></a>"
document.getElementsByClassName('cont-product-variacion-color')[0].firstElementChild.innerHTML = resultado;
}
});
So I was in the presumption that this function
button.onclick = exampleFunk;
would give me a handler on each button when I click them, but it doesn't. When replacing it with:
button.onclick = alert("bananas");
I'm getting alerts at page onload. The problem is already solved with this:
button.setAttribute("onclick", "removeIssue(this)");
Out of curiousity... What's going on?
edited layout of post
EDIT
var issues = [];
window.onload = function () {
//alert("venster geladen");
issuesToList()
}
function issuesToList(data) {
/*alert(
"array length is " + data.issues.length + "\n" +
"total_count is " + data.total_count + "\n" +
"limit is " + data.limit + "\n" +
"offset is " + data.offset + "\n" + ""
);*/
for (i = 0; i < data.issues.length; i++) {
issue = data.issues[i];
createIssue(issue);
}
}
function createIssue(issue){
var id = issue.id;
var tracker = issue.tracker;
var status = issue.status;
var priority = issue.priority;
var subject = issue.subject;
var description = issue.description;
var assignee = issue.assignee;
var watchers = issue.watchers;
var ticket = new Issue(id, tracker, status, priority, subject, description, assignee, watchers);
issues.push(ticket);
var button = document.createElement("button");
button.innerHTML = "-";
button.onclick = function (){ alert("bananas")};
//button.setAttribute("onclick", "removeIssue(this)");
var item = document.createElement("div");
item.setAttribute("id", id);
item.appendChild(button);
item.innerHTML += " " + subject;
var container = document.getElementById("container");
container.appendChild(item);
}
function removeIssue(e){
var key = e.parentNode.getAttribute("id");
var count = issues.length;
if(confirm("Confirm to delete")){
for(i=0; i<count; i++){
if (issues[i].id == key ){
issues.splice(i,1);
var element = document.getElementById(key);
element.parentNode.removeChild(element);
}
}
}
}
function Issue(id, tracker, status, priority, subject, description, assignee, watchers){
this.id = id;
this.tracker = tracker;
this.status = status;
this.priority = priority;
this.subject = subject;
this.description = description;
this.assignee = assignee;
this.watchers = watchers;
}
EDIT
<body>
<h1>List of Issues</h1>
<div id="container"></div>
<script src="http://www.redmine.org/issues.json?limit=10&callback=issuesToList"></script>
</body>
You need to mask the alert in a function:
button.onclick = function (){ alert("bananas")};
As such:
var btn = document.createElement("BUTTON");
var t = document.createTextNode("CLICK ME");
btn.appendChild(t);
btn.onclick = function() {alert("bananas")};
document.body.appendChild(btn);
Whats going on?
You alert() is executed on page load because its a function call. When the execution of your script reaches that line your assignment
button.onclick = alert("bananas");
is actually executing the alert statement and not assigning it to button.onclick
You can bind arguments to the function so that it returns with the function you want it to call using your arguments (with additional arguments passed later added on to the end). This way doesn't require writing extraneous code (when all you want to do is call a single function) and looks a lot sleeker. See the following example:
button.onclick = alert.bind(window, "bananas");
An unrelated example of how it works in your own code is like this:
var alert2 = alert.bind(window, 'Predefined arg');
alert2(); // 'Predefined arg'
alert2('Unused'); // 'Predefined arg'
For IE, this requires IE9 as a minimum. See MDN for more information.
EDIT: I've looked closer at your code and there was one significant change that was needed for it to work... You cannot add onto the innerHTML when you've added JavaScript properties to a child element. Changing the innerHTML of the parent element will convert your element into HTML, which won't have the onclick property you made before. Use element.appendChild(document.createTextNode('My text')) to add text dynamically.
See a functioning example here: http://jsfiddle.net/2ftmh0gh/2/
I made a function to add <a> tag in chat text and it worked fine, but it seems the variables of the function are shared between different instances of the function called from different chat rooms. I thought function variable were local, can anyone explain why I'm encountering this problem? Well I found out the code was wrong and a <p> tag the ajax function was adding to the string was interfering with this function. i fixed it by adding a space before the conflicting <p> tag and now it works fine...updated the code with english variable names too :)
function ajoutertagdelien(dataChat)
{
if (dataChat)
{
}
else
{
dataChat = " ";
}
var chatsendvar = dataChat;
var linkLocation, chatStringLeftPiece, chatfinal = "", chatStringRightPiece, lienfin, LinkAlone, LinktagString, LinkPiece;
var linkTagA = new Array();
var variablelocation = new Array();
var variablechatsend = new Array();
var increment=0;
var earlierLinkLength = 0;
linkLocation = chatsendvar.indexOf("www.");
while (linkLocation != -1) {
increment++;//
if (linkLocation != -1)
{
chatStringLeftPiece = chatsendvar.substring(0,linkLocation);
LinkPiece = chatsendvar.slice(linkLocation,chatsendvar.length);
lienfin = LinkPiece.indexOf(" ");
LinkAlone = LinkPiece.substring(0,lienfin);
chatStringRightPiece = chatsendvar.substring(((lienfin + linkLocation)),chatsendvar.length) ;
console.log( chatStringLeftPiece + " droit et gauche " + chatStringRightPiece + " number of theloop in the while=" + increment);
LinktagString = "<a target='_blank' href='http://"+ LinkAlone+"'>"+LinkAlone+"</a>";
chatsendvar = chatStringLeftPiece + " " + chatStringRightPiece;
linkTagA.push(LinktagString);
variablelocation.push(chatStringLeftPiece.length + earlierLinkLength);
earlierLinkLength = earlierLinkLength + LinktagString.length +1;
}
linkLocation = chatsendvar.indexOf("www.");
}
for (var x = 0, j = linkTagA.length; x<j; x++) {
chatsendvar = chatsendvar.split('');
chatsendvar.splice((variablelocation[x]),1," "+linkTagA[x]+" ");
chatsendvar = chatsendvar.join('');
};
return chatsendvar;
}
All this code to detect links in a text?
I know that's not what you asked, but this small function can do this. It can detect links beginning with www. or http:// and even handles url parameters, like ?a=1&b=2. Here is a demo fiddle.
The regex could be modified to handle https:// or url encoding for example, but you get my point.
function makeLinks(text) {
return text.replace(/(?:http:\/\/|(www\.))([\w\d.\/\?&=]+)/gi, '<a target="_blank" href="http://$1$2">$1$2</a>');
}
For checking server side validation errors, I am using "afterSubmit" property of jqGRid.
afterSubmit: checkForErrors
And my checkForErrors is something like this:
function checkForErrors(response,postdata){
var success = true;
var message = ""
var json = eval('(' + response.responseText + ')');
if(json.errors.length>0) {
success = false;
for(i=0; i < json.errors.length; i++) {
message += json.errors[i] + '<br/>';
}
}
var new_id = null;
return [success,message,new_id];
}
The only thing i need to fix is change the default error class/style used by jqgrid (ie. ui-state-error), to my custom css class. How can i do that.
Thanks!
Try this:
function checkForErrors(response,postdata){
var success = true;
var message = ""
var json = eval('(' + response.responseText + ')');
if(json.errors.length>0) {
success = false;
for(i=0; i < json.errors.length; i++) {
message += json.errors[i] + '<br/>';
}
}
var new_id = null;
//Here pass the right class name instead of ".dialog" which you are using in your code
$(".dialog").find(".ui-state-error").removeClass("ui-state-error").addClass("newClass");
return [success,message,new_id];
}
I made a web app that loads images using jquery, ajax and json. I got it to work in Firefox, but alas, Safari and Chrome remain stubborn.
It has to do with a "race condition" where images don't load quickly enough, so I have a load event as well as a trigger event to wait until all images are loaded before appending the html to a container div.
Here is the link to the page that works in FF:
http://chereecheree.com/dagworthy/style.html
And some code:
var aSectionImages = new Array;
//count how many images are in a section:
var aImagesCount = new Array();
//count how many images of a particular section have been loaded
var aImagesLoaded = new Array();
var htmlString;
var jsonStyleImages = "images.json"
var jsonNavImages = "imagesNav.json";
//container div:
var scrollableArea = $("#scrollableArea");
$.getJSON(jsonNavImages, getNavIcons);
$.getJSON(jsonStyleImages, makeScroller);
//trigger this function on load event:
function imageLoaded(oImg){
//get the name of the section of images:
var locSectionId = (imageInSection(oImg.src)).replace(/\s|'/g, "_");
//get the file name of the current image
var locFileName = getFileName(oImg.src);
if (aImagesLoaded[locSectionId]===undefined){
aImagesLoaded[locSectionId] = new Array;
};
//check if it has already been loaded by seeing if it exists in the array of loaded images:
var inArray = false;
inArray = $.inArray(locFileName, aImagesLoaded[locSectionId]);
if (inArray == -1) {
//array.push returns the new length of the array:
var tempLength = aImagesLoaded[locSectionId].push(locFileName);
}
if (tempLength==aImagesCount[locSectionId]){
htmlString += "</div>";
scrollableArea.append(htmlString);
//after the html has been appended, force it to be 1000 px -- totally unstable hack.
scrollableArea.width(1000);
}
}
//helper function to get section name of a loading image:
function imageInSection(src){
var resultId=false;
var locFileName = getFileName(src);
for (var k = 0; k < aSectionImages.length; k++){
for(var j=0; j < aSectionImages[k].images.length; j++){
tempSrc = aSectionImages[k].images[j].src.split("/");
tempFileName = tempSrc[tempSrc.length-1];
if (tempFileName == locFileName) {
resultId = aSectionImages[k].id;
}
}
}
return resultId;
}
//helper function to get the file name of a loading image:
function getFileName(href){
var resultFileName=false;
var locSrc = href.split("/");
resultFileName = (locSrc[locSrc.length-1]);
return resultFileName;
}
//function called when ajax request is successful -- it puts together the html string that will be appended to the containter div
function makeScroller(data){
aSectionImages = data;
for (ii=0; ii<aSectionImages.length; ii++){
var locData = aSectionImages[ii];
var locId = locData.id.replace(/\s|'/g, "_");
aImagesCount[locId] = locData.images.length;
htmlString = "<div id=\"" + locId + "\">";
for (jj=0; jj<locData.images.length; jj++){
var oImage = new Image();
var locImage = locData.images[jj];
$(oImage)
.load(function(){
imageLoaded(oImage);
})
.attr("src", locData.images[jj].src);
if (oImage.complete && oImage.naturalWidth !== 0){
$(oImage).trigger("load");
}
//alert (oImage.width);
locImage.id ? locImage.id = " id=\""+locImage.id+"\" " : locImage.id = "";
htmlString += "<img height=\"" + locImage.height + "\"" + " width=\"" + oImage.width + "\"" + locImage.id + " src=\"" + locImage.src + "\" />";
}
}
}
But it's probably best to look at it online, as there is a plugin that's used.
Anyhow, the computed style for the container div shows up at "0px" sometimes, which is why I'm forcing it to "1000px" but that hack is not very stable.
Any ideas would be greatly appreciated.
Thanks!
--Daniel.
In this section:
$(oImage)
.load(function(){
imageLoaded(oImage);
})
.attr("src", locData.images[jj].src);
if (oImage.complete && oImage.naturalWidth !== 0){
$(oImage).trigger("load");
}
image.naturalWidth isn't available in all browsers (so undefined !== 0 won't be a correct check), but you don't need it to use it, just rearrange the code, like this:
$(oImage).one('load', function(){ imageLoaded(this); })
.attr("src", locData.images[jj].src)
.each(function() {
if (this.complete) $(this).trigger("load");
});
This uses .each() to loop through after setting the src and triggers the load event in case it came from cache (this.complete being instantly true indicates this). The .one() call ensures the load event only fires once, whether from cache or a normal load.