How to fix the DataTables.net Internet Explorer error: "Unable to get value of the property 'style': object is null or undefined"

On one of my latest management projects I had to test and ensure that the project would work as expected in Internet Explorer. With the exception of a few style issues, which are to be expected when IE testing, I noticed that my DataTables.net code was returning the following error: Unable to get value of the property 'style': object is null or undefined. This was only happening in Internet Explorer 7 and below.

Usually IE would return this error message if the number of columns I was declaring in the DataTables javascript did not match the number of headers I had in my HTML. However, I knew that I did have the correct number of headers as the code works as expected in all the other browsers.

When I went to investigate my code I noticed a rogue coma on the last element in my column collection when I was declaring my DataTable. My code looked something like this:

$(document).ready(function () {
            oTable = $('#dt').dataTable({
                "sAjaxSource": 'AllUsers/',
                "aoColumns": [
			            { "mDataProp": "Firstname" },
			            { "mDataProp": "Surname" },
			            { "mDataProp": "Email" },
		            ]
            });
        });

When I removed that last coma after my Email column everything worked as expected. Now my code looks like this:

$(document).ready(function () {
            oTable = $('#dt').dataTable({
                "sAjaxSource": 'AllUsers/',
                "aoColumns": [
			            { "mDataProp": "Firstname" },
			            { "mDataProp": "Surname" },
			            { "mDataProp": "Email" }
		            ]
            });
        });

It's weird that IE had an issue with this and the other browsers were ok with it. I guess it's just down to the different rendering engines in the browsers. It was incorrect before but the other browsers ignored the issue. Thankfully this was an easy fix!

How to get the id of a textbox that is using jQuery UI AutoComplete

Recently I had a need for getting the id value of a textbox that was using the jQuery UI AutoComplete plugin. I wanted to pass this id value as a parameter and use it in my Ajax call to my database. To add some extra complexity, my project was using the AutoComplete plugin on numerous textboxes. I didn't want to make a function for each textbox that would be using the AutoComplete so I had to set it up in a slightly generic way.

The trick to getting this working is to wrap your AutoComplete function call around an 'each' loop for the textboxes so that the 'attr' function becomes available to use and allows us to grab the id value we need to use in our Ajax call.

Below is the code I used. As you can see I do a 'each' call for every textbox that uses the 'tb' css class. If you've used the AutoComplete plugin before the rest of this code should be familiar to what you're using. If not, I'd recommend taking a look at the plugin documentation.

$("input:text.tb").each(function () {
        var thisElement = $(this);
        $(this).autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "FetchLocationList/TestPage",
                    data: "{ 'loc': '" + request.term + "', 'textboxid': '" + thisElement.attr("id") + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataFilter: function (data) { return data; },
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                value: item.Name,
                                key: item.Code
                            }
                        }))
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    }
                });
            },
            minLength: 3
        });
    });

Fix for CKEditor with MVC3 when using multiple submit buttons

I had an issue this weekend while updating some code from WebForms to MVC3 when using the brilliant CKEditor. Many of our forms display 2 submit buttons - one for publishing and one to save as a draft. When using WebForms there was never any issue with this. I'd just make 2 <asp:Buttons>, add some On_Click handlers and everything was great. With MVC3 I noticed that when using the CKEditor on my forms that I was having to click on the submit buttons twice before the page would submit.

At first I thought this was down to the MVC validation. I removed the validation but the issue still occured. "Ah, it must be the way I handle the postback with the 2 buttons!", I thought, but this didn't seem to work either. I put my button logic and the validation back on my page and removed the class I had put on the textarea of my form to get the CKEditor working and everything worked as expected. The issue was down to the CKEditor and how it was handling multiple submit buttons in a single form. You need to force CKEditor to update the textarea before carrying on with posting the page.

I did some searching on the CKEditor forums and on Google. I came across a piece of javascript that you can add to your webpage to work around this issue (asp.net forums link). Simply add the following to your page and it will resolve the '2 clicks to submit' issue you're having. Note you can add other events to this code if you want but paste and on keyup events should cover you 99% of the time.

$(document).ready(function () {
    for (instance in CKEDITOR.instances) {
        CKEDITOR.instances[instance].on("instanceReady", function () {
            //set keyup event
            this.document.on("keyup", function () { CKEDITOR.instances[instance].updateElement(); });
            //and paste event
            this.document.on("paste", function () { CKEDITOR.instances[instance].updateElement(); });
        });
    }
});

How to fix the jQuery live event not firing for submit buttons in IE

I was recently working on our new website for Dragnet Systems when I stumbled onto an issue with submit buttons not working as expected in Internet Explorer when I was using the .live event for jQuery. Everything works as intended in Firefox, Safari, Opera and Chrome but Internet Explorer was completely ignoring the form submit clicks.

After doing some reading over on the jQuery forums it turns out that this is an issue quite a few people have run into. The solution I went with was to use a third party plugin called LiveQuery. This plugin ensures that after the DOM has loaded my elements are correctly registered to my events and will work as expected.

Using the script couldn't be easier, simply download the file from the LiveQuery plugin page and in your code use .livequery instead of .live.

There's a good chance that this will be fixed in later releases of jQuery but for now (1.4.2) this is a nice workaround.

How to add one day to the calendar date selected using jquery ui

I recently has an email come into me asking about a previous post I did regarding the jQuery UI date picker. This person was looking for a way to add some extra functionality to the date picker example I had that would auto default to setting the drop off date textbox value to be one day ahead of the pickup date.

To do this all that is required is to add an extra function within the document.ready() function that fires when the pickup date is changed, add one to the date entered and then put that value into the drop off box. The code to do this is:

$('.pUpDate').change(function() {
    var nextDayDate = $('.pUpDate').datepicker('getDate', '+1d');
    nextDayDate.setDate(nextDayDate.getDate() + 1);
    $('.dOffDate').datepicker('setDate', nextDayDate);
});

Building on the previous examples demo, below is a link to download a working example that includes the above new code snippet.

Download this demo

Use jquery to scroll to a specific section on your page from a link or a button.

This little feature can be very handy if you want to auto scroll the page to a particular section. I have used this previously on sites where I want the user to be shown error messages that are on top of a large form. So instead of the user clicking submit and nothing happening the user would click submit and if there were any errors the page would scroll to the error messages on the top of the form.

To achieve this effect create a javascript function like this:
(Thanks to David King from OneDayLater.com for the Opera fix for the button click event!)

function goToByScroll(element) {
    var el = $.browser.opera ? $("html") : $("html, body");
    el.animate({ scrollTop: $(element).offset().top }, 'slow');
}

Now call the above function whenever you want the screen to move to a point. For our example we will scroll on a button click or from a link click using the code below:

$(document).ready(function () {
        //scroll if link click to section2
        $('#Section1 a').click(function (evt) {
            evt.preventDefault();
            goToByScroll('#Section2');
        });
        
        //scroll if button click to section 1 
        $('#SubmitForm').click(function (evt) {
            evt.preventDefault();
            goToByScroll('#Section1');
        });
});

You can view a working demo of this in action here. Simply Right Click and View Source to see the code.

How to know if a checkbox has been selected when submitting a form using jquery

If you have a checkbox on your form that has to be selected before you want the user to continue you can use jquery to check if it has been selected by doing something like the following:

$(document).ready(function () {
        $('#SubmitForm').click(function () {
            if ($('#Terms').attr('checked') == false) {
                alert('please select the terms and conditions before continuing.')              
                return false;
            }
        });
    });

Your html form must have a checkbox with an id value of Terms to match the javascript above.

    
    
    

If it is crucial to have a checkbox ticked before continuing in your website or app you should validate on the server side as well but the above script should help to get you started.

Click here for a simple demo of this in action.

RichardReddy.ie goes live showcasing the lastest work by Richard Reddy

Richard Reddy Cork Web Developer

<shamelessPlug>I've been meaning to setup my own domain name for a while now. During December last year Blacknight.com were offering .ie domain names for only €2.99 so I couldn't resist and bought richardreddy.ie.

The site design is using BCProducties' vCard template which was given away for free for January to members of ThemeForest. If you're quick you might still be able to download the file for free here.

Over the coming days I will update the work section of the site so that it contains details of my latest work. It's nice to finally have something a bit more professional to use rather then reddybrek ;)</shamelessPlug>

How to use a JQuery UI modal box with asp.net

View Demo | Download Source

I was recently asked to look into making a JQuery UI dialog box (aka a modal box) work with asp.net. I thought it would be straight forward but as with anything in asp.net it turned out to be a little bit trickier than I had initially thought. Part of the problem was that I wanted to put the dialog box on an asp.net submit button and depending on the user's choice either submit the page or cancel the action.

Thankfully I stumbled across this great article over at DeviantPoint. It was pretty much exactly what I needed. However, for my example I needed to only show the dialog box if any of the checkboxes on the screen were not selected. In other words a normal postback would occur if every check was selected but if there were any checkboxes not selected the user would be asked to confirm their action.

If you take a look at my very basic demo page you will see exactly what I'm talking about. You will find all of the code within the source files I have posted for download but below is a brief overview of what is going on.

View Demo | Download Source

HTML used:


    
    
    

This is a top class widget. Features include...

Below are the required items for this product to function correctly:
Required Item 1 Required Item 2
Required Item 3 Required Item 4

Javascript used:


C# Codebehind:

if (!Page.IsPostBack)
        {
            //this line is used to hold the exact postback function call used by the asp.net button
            this.MsgBoxContinue.Value = Page.ClientScript.GetPostBackEventReference(AddToBasket, string.Empty);

            //ensure the postback message is blank on load
            PostBackMsgTest.Text = ""; 
        }

        if (Page.IsPostBack)
        {
            PostBackMsgTest.Text = "Content posted back successfully.";
        }

jQuery UI date picker - how to set the start date of your second calendar

set the mindate of a second calendar using jquery ui

If you haven't already looked into using the jquery UI calendars, you really should! One of my latest projects, www.hertzflydrive.com, uses these calendars on the homepage. They are quick to setup and offer loads of options that make them very flexible for anyone looking to use date pickers on their forms.

One of the most common setups is to use two calendars to let users pick 'From - To' dates. Placing two textboxes and setting them up to use the calendars is easy (and for this post I am assuming you can at least do that much) but what if we only want our second calendar to only allow the user to select dates on or after the date entered in the first calendar?

Well the good news is that this is easy to do using a custom function that is called before the calendar is displayed to the end user. The script below shows the jQuery for setting up two calendars on your form and the custom function to ensure that the dates the end user selects on the second calendar are either after today's date or after the value entered in our 'From' calendar.

jQuery - save as calendar-config.js in a folder called scripts:

$().ready(function() {
    $('.pUpDate, .dOffDate').datepicker({
        numberOfMonths: 2,
        showButtonPanel: true,
        beforeShow: customRange,
        dateFormat: 'dd-mm-yy',
        showOn: 'both',
        buttonImage: 'images/calendar-icon.gif',
        buttonImageOnly: true,
        buttonText: 'Show Date Picker'
    });
});
function customRange(a) {
    var b = new Date();
    var c = new Date(b.getFullYear(), b.getMonth(), b.getDate());
    if (a.id == 'DropoffDate') {
        if ($('.pUpDate').datepicker('getDate') != null) {
            c = $('.pUpDate').datepicker('getDate');
        }
    }
    return {
        minDate: c
    }
}

The custom range function above should be self explanatory. We pass in the id of the element we clicked on (i.e. which textbox we're currently in) and if that textbox is the drop-off textbox we want to set the min date to be the value entered in the Pick-up textbox, assuming it has a value.

HTML:


    date picker dual calendar example
     
    
    
    
    
    



    
    

    
    

To help you get started you can download a working example of this demo here - min date jquery demo.zip (67.37 kb). To view it in action head over to hertzflydrive.com.