Kendo Grid "TypeError: u is undefined"

possible reason you may find this nondescript error

TypeError: u is undefined

I was getting this strange error while using KendoGrid which I had used many times before and I couldn't figure out why. I was simply calling:
$('#grid').kendoGrid();

On a simple table, nothing special. Turns out it was simply because I had used some <th> in the <tbody>, but it can only be located in the <thead>.

MVC Bundling not working on Azure deploy

working locally, but not on deploy

When using your bundler, everything may work fine, but quirks often pop up on Azure deployment, these are some of them I came across:

Styles/Javascript not rendering at all

This my be because your names resemble your directory structure, which apparently it does not like. For example, if this is your Bundle:
bundles.Add(new StyleBundle("~/Styles/Metro").Include(
            "~/Styles/Metro/metro-bootstrap.css",
            "~/Styles/Metro/metro-ui-icons.css"));

And you use the render:
@Styles.Render("~/Styles/Metro")

It will not render on Azure! Simply change it so your render string does not resemble your actual directory structure, and it will work:
bundles.Add(new StyleBundle("~/Styles/MetroCss").Include(
            "~/Styles/Metro/metro-bootstrap.css",
            "~/Styles/Metro/metro-ui-icons.css"));

And you use the render:
@Styles.Render("~/Styles/MetroCss")

Notice that the directory is ~/Styles/Metro but the render string is ~/Styles/MetroCss.

If that is not it, be sure you are using
@Styles.Render("~/Styles...")

for css, and:
@Scripts.Render("~/Scripts...")

for Javascript.

Images or Fonts not rendering

This is because you assume things will behave the same when they are up in Azure, which is not always the case. If you have this stuff outside of the ~/Content/ folder, your program will not, by default, know how to handle it. You will get a Controller error if you try to navigate to it manually.

The answer? Simply move everything somewhere within the ~/Content/ folder which MVC makes public by default. Don't forget to update your css and JavaScript accordingly!

Otherwise you can make a controller to handle these requests, but that involves more work.

jQuery moveTo() plugin

simple way to move an element from A to B

Say you have these elements:
<ul id="A">
    <li id="L1">Stan</li>
    <li id="L2">Arnold</li>
</ul>
<ul id="B">
</ul>

And you want to move 'L1' (Stan) to ul 'B' - using this simple short plugin:
(function ($) {
    $.fn.moveTo = function (selector) {
        return this.each(function () {
            var element = $(this).detach();
            $(selector).append(element);
        });
    };
})(jQuery);

You can do that with this:
$('#L1').moveTo('#B');

Now you have this in your DOM:
<ul id="A">
    <li id="L2">Arnold</li>
</ul>
<ul id="B">
    <li id="L1">Stan</li>
</ul>

Or, similarly, you can do something like this:
$('li').moveTo('#B');

Now you have this in your DOM:
<ul id="A">
</ul>
<ul id="B">
    <li id="L1">Stan</li>
    <li id="L2">Arnold</li>
</ul>

Monitoring a DOM Element for Modification with jQuery

'watching' an element for any change within it

I recently ran into a situation where I had to modify a site that relied on an incredibly obfuscated and impossible to understand javascript file. I had to add in some elements after everything was populated with some function I didn't get, so I had to wait until a specific element was populated to do anything. Turns out the DOMNodeInserted event is what I needed:
var title = $("b.facility");
var title = $('#title');//the element I want to monitor
title.bind('DOMNodeInserted', function(e) {
    alert('element now contains: ' + $(e.target).html());
});

Pretty simple, but took me forever to figure out...

Javascript replaceAll function

javascript .replace() only replaces on instance of a character/string, this will replace them all (with no looping)

This may be well know, but I did not realize this until it broke a js function where I was converting currency to integers; anything over $999,999 would not work right, apparently because the extra comma when you hit $1,000,000 was not getting replaced.

At first I went through and looped though a string, but that turned out to be ugly, and likely not as efficient as it could be. So I rooted around with some regexs and figured out the following, turns out it is clean and simple:

function replaceAll(txt, replace, with_this) {
  return txt.replace(new RegExp(replace, 'g'),with_this);
}

So now, replaceAll('1,000,000', ',', '') will return '1000000' and *not* '1000,000'.

Use and Manipulate Asp.Net Validators with jQuery and/or Javascript

Asp.Net has some great validation included - no need to learn new validation, just grab them with client-side scripting

The problem I found when going into jQuery validation, is that they mostly seem to assume that you can have more than one form on your page; which, for us Asp.Net devs, is not the case. After some digging, I figured out how to use the current validators which I am already familiar with (RegularExpressionValidator, RequiredFieldValidator, etc.) and just hook into them with javascript; no need to reinvent the wheel. It is very easy, and we don't lose the server-side validation that is so great with the Asp.Net validators (if you call on it that is).

want to make a certain validator(s) fire?

Let's say I have a RequiredFieldValidator named 'rfvFirst' and I want it to test for validation on the click event of the element with id 'some_link'. With jQuery, this is what I would do:
$("#some_link").click(function() {
    ValidatorValidate($("#<%= rfvFirst.ClientID %>")[0]);
});

Now, the ErrorMessage of 'rfvFirst' will show if it is not valid - it will behave just as if you tried to submit the form, but just for that validator itself. Notice that I am using <%= rfvFirst.ClientID %> which will pull the crazy Asp.Net id that is produced in Asp.net which is often something strange like 'ctl00_ContentPlaceHolder1_rfvFirst'.  Now, if you want to use a class or something else to select the Validators, that is fine too.  This will fire all of the Validators that have the CssClass 'fire':
$(".fire").each(function() {
    ValidatorValidate($(this)[0]);
});

want to have a button/link cause validation and only work if the page is valid?

For this, you need to make sure your validators each have a ValidationGroup set. In this example I am attaching it to a button with id 'submit' and the ValidationGroup 'new'. Simply attach the click event to Page_ClientValidate() method:
$("#submit").click(function() {
    return Page_ClientValidate('new');
});

This was the only method I found that actually returned something that could be used to tell if the page was valid (I am far from a JS pro). There is likely more ways to do this and I am interested in any that people have found!

want to stroll through the validators?

The are all held in an object (array) 'Page_Validators' and you can access it like any other array, looping or whatever. This will look through and output into the 'report' element the ids of all the Validators you have on your page:
for(var i=0,len=Page_Validators.length;i<len;++i){
    $("#report").append($(Page_Validators[i]).attr('id'));
    $("#report").append("<br />");
}

Finding web hosting reviews is the first step when you plan to build a website. It will help you ensure a great looking site.

Javascript page modifiers

Simple way for your users to modify how a page looks

I have been asked more than once on how to make javascript (or as everyone asks now, 'AJAX') methods to modify a page.  It is very simple and easy to implement.

 

In the supplied example, I show modifiers for both single areas, and the whole page.  I know I chose hideous colors, but live with it, it's just an example...

 

First, what you need to do is some simple JS that allows you to change the style attributes of your html, here are both sets of functions; ones that apply to the whole page, others that apply to specific parts:

 

[code:js]

//apply to the whole page
function fontSize(number)
{ document.body.style.fontSize = number + "em"; }
function fontColor(color)
{ document.body.style.color = color; }
function backgroundColor(color)
{ document.body.style.backgroundColor = color; }

//apply to a specific part of the page
function divFontSize(number, div)
{ document.getElementById(div).style.fontSize = number + "em"; }
function divFontColor(color, div)
{ document.getElementById(div).style.color = color; }
function divBackgroundColor(color, div)
{ document.getElementById(div).style.backgroundColor = color; }

[/code]

 

As you can see,that is about as simple and straight-forward as you get, then simple call them like this:

 

[code:html]

<div>
    Single Div Modifiers:
    <a href="javascript:divFontSize('0.8', 'div1')" style="font-size:0.8em;" >small</a> |
    <a href="javascript:divFontSize('1', 'div1')" >medium</a> |
    <a href="javascript:divFontSize('1.2', 'div1')" style="font-size:1.2em;">large</a> |
    <a href="javascript:divFontColor('black', 'div1')" style="color:Black;">black</a> |
    <a href="javascript:divFontColor('navy', 'div1')" style="color:Navy;">navy</a> |
    <a href="javascript:divFontColor('green', 'div1')" style="color:Green;">green</a> |
    <a href="javascript:divBackgroundColor('white', 'div1')" style="background:white;">White</a> |
    <a href="javascript:divBackgroundColor('grey', 'div1')" style="background:grey;">Grey</a> |
    <a href="javascript:divBackgroundColor('yellow', 'div1')" style="background:yellow;">Yellow</a>
</div>

<div id="div1">
    Lorem ipsum dolor sit amet.
    Mauris nunc odio, molestie quis.
    Sed ac orci eu diam dapibus scelerisque. 
    Phasellus in nulla a justo dignissim suscipit.
    Class aptent taciti inceptos himenaeos.
</div>

[/code]

 

In the code shown above, the modifiers will only affect whatever is in div1.  And there you have it.

 


 
 
 

 

Awesome JavaScript DateTime Picker

A great tool that is completely customizable and can do more than your current DateTime picker!

The folks at Zapatec came up with an amazing and free customizable DateTime picker.  You can check out all sorts of demos here, or make your own and use their javascript (no downloads) here.  I love this tool, gonna be using it a lot from now on, thanks Zapatec!  I included an example of how to use it in asp.net.  Also, I have found it easiest to use the wizard on their page to customize it.



Text Input Watermarks using Javascript (IE Compatible)

Simple way to add watermarks to your textboxes for a little flair in your input forms

I have always used the TextBoxWatermark control that is supplied with the AjaxControlToolkit which is very easy to use and I highly recommend it.  But recently I was asked to figure out a way without using 3rd party tools, hence in JavaScript.  At first I figured it was going to be simple, just clear the text when you click on the box and maybe change the background color.  Simple, that works.   Thats when I ran into my next problem.

 

I wanted a textbox that was forr passwords, it would start out and say 'password' but then when you clicked on it, that would disappear and it would become a type="password" box (display text as: ******).  It worked flawlessly! ...in non-crappy browsers.  IE7 dumped all over my dreams yet again and left me with a Javascript error.  Turns out you can't change the type property in IE7 (apparently it works in IE6???) which is completely stupid.

 

So, I did some good old googling which brought me here to find out that in order to change type, you now have to make an entire new object and swap it out with the old one.  So after that, it works, but my focus is all screwed up: I click on the blank, the password text disappears, but the cursor is not in the textbox I just clicked?!  That brought me here which showed me a crazy way to reset focus on a lost object:

window.tempObject = newObject;
   setTimeout("tempObject.hasFocus=true;tempObject.focus();",1);

Now everything seems to work just fine.  BUT, they aren't.  For one thing, I had had an onblur statement in my textbox originally (not in the example, but for discussion purposes) and since the new object did not have an onblur, I had to make sure to re-add that back in.  Also, the same loss goes for CSS class, but that might want to change, so I added a new field into the function to take into account a new CSS class.  If it is left blank, it will inherit the old CSS class if there is one, or simply have no class like Britney Spears. 

 

Ok, so I *thought* that would be easy, but IE comes back again to spite me.  For most browsers, you can set Object.setAttribute("onblur", "JSmethod") but IE decides that isn't good enough, so you have to to this Object.onblur = function(){js_function(god, damnit, ie);}; (from this thread).  Ok, now that we have that fixed, we can look at the CSS class.  It's mostly the same, but this is yet another IE specific problem.  You need to include two different declarations: Object.setAttribute("class", "css_class"); for most browsers and Object.setAttribute("className", "css_class"); for IE.  This time the IE fix/hack will not work for cross-browser compatibility.  So here is the finished JS:

 

[code:js]

 function makePassword(oldObject, newClass)
{
    //newclass is the new css class to pass to the textbox
    //otherwise leave it blank ('') to inherit it's old class
    //or if there isn't one, have no class
    var newObject = document.createElement('input');
    //only switched to password if the original text was password
    newObject.type = (oldObject.value == 'password')?'password':'text';
    if(oldObject.id) newObject.id = oldObject.id;
    /// this decided whether to keep the old class or get a new one
    var cssClass = (oldObject.className && newClass.length < 1)?oldObject.className:newClass;
    newObject.setAttribute('className', cssClass);// for IE
    newObject.setAttribute('class', cssClass);// for others (these are both needed)
    //the following is hard coded to add onblur functionality to the control
    //newObject.setAttribute('onblur', 'blurred(this)');// this would work if it wasn't for IE
    newObject.onblur = function(){blurred(this,newClass);}; // because of IE
    oldObject.parentNode.replaceChild(newObject,oldObject);//this is necessary because of IE
    //this is needed since a focus() will only work the second time since it happens too 'soon'
    window.tempObject = newObject;
    setTimeout("tempObject.hasFocus=true;tempObject.focus();",1);
}

[/code]

 

Remember though that you will have to validate that the original values are not in the textboxes when the user submits, as they will not be empty initially.  Here is a fully working example to mess with, it shows how to use it both for a simple watermark/mask and also with a password field change.  It also includes how to add javascript function calls and deal with changing (or persistent) css: