Blog, Web Development

Working with Radio buttons and jQuery

Working with Radio buttons and jQuery Radio buttons are one of the essential HTML elements that you can find in almost any website that contains a form for users to enter data. In this blog today we will do the following:

  • Add radio buttons dynamically using jQuery
  • And, get the value and text of the selected radio button using jQuery

First you need a standard boiler plate html page that has a reference to the jQuery library. For this example we will use the Google jQuery CDN to pull the library on our page. At this stage, you page should look like this:

Now we can add our basic html elements. The page will consist of 2 buttons and 1 div where the radio buttons will eventually be displayed. Within the body add the following html:

Finally, between the closing </body> and closing </html> tags add the following javascript code:

The first method uses a string array in order to populate the radio buttons with values and text. We also use the .append method to add the radio buttons to the DOM and make them visible. The first time that we iterate through the array, we also set the radio button to ‘checked’ so that the user can see the first option pre-selected when presented with the radio buttons. This is optional and you can of course opt out from having any radio buttons implemented.

The second method uses jQuery in order to retrieve the value and the test of the selected radio button and displays an alert (message box) with the selected values. For me, the trickiest part was getting the selected text, especially if it is different from the radio button value itself.

You can see a working version of this code on jsFiddle

Happy coding…

.NET, Blog, Software Development, Web Development

Accessing local data files using Html and Chrome

During the development and testing stages of a new website, there are time when you may need to access Json or xml data stored in a local file. The test site can be running under Visual Studio, IIS Express or even IIS. I recently had to quickly test some javascript code that interacted with Json data. I was trying to debug using Chrome’s Developers tools but I was getting an error at every execution.

The method was doing nothing more than this:

By default, Chrome does not allow javascript  to interact with local file systems.  If you try, then you will be greeted with the following error message:

XMLHttpRequest cannot load file:///C:/path/to/C:/Temp/testdata.json. Origin null is not allowed by Access-Control-Allow-Origin.

However, Chrome offers a flag that lets you turn on this feature as described below (please note that the steps are for Windows 7-8 but the same logic applies to Mac OS X)

  1. Close down your Chrome browser (make sure you close all instances if you have multiple windows open)
  2. Go to Run and type the following command:
    chrome.exe –allow-file-access-from-file
  3. Hit enter

For all you Mac fun boys out there (me included as I’m typing this on my Mac Book Pro Retina) the command equivalent for step 2 is:

Run Type “open /Applications/Google\ –args  –allow-file-access-from-file”, no quotes.

Now you should be able to do the following in your code (snippet below)

Happy Coding…

Blog, Software Development, Web Development

Tidy up your forms with horizontal sliding divs using JQuery UI

Many websites still make use of lengthy scrollable forms or numerous page post backs when requesting input from their users, e.g shopping cart check outs etc. jQuery and jQueryUI give developers the opportunity to significantly improve the overall UI experience.

In this tutorial, we will look into creating sliding panels/divs that respond to user input and allow the users to navigate through the data entry process in a nice, fluid way.

First we need to ensure that we reference the appropriate libraries:

  • jQuery 1.9.0
  • jQueryUI 1.9.2

Then we need to create our html elements:


The code above will create an “outer” (container) div and then 3 divs with some navigational buttons (GO and BACK).

Next we will decorate the elements using css. This can be placed either within the html page or an external file that you will need to link to. The css is listed below:

Notice the use of the z-index to stack up the divs one on top of the other. The higher the z-index the higher the div will be placed/stacked. Also, the colors used for this example have only been chosen in order to easily distinguish between the different panels.

And finally, the JavaScript code that will tie everything together and will provide the necessary animation:

The JavaScript code above will cause each individual div to slide to the left until it’s hidden when the div containing the GO text is clicked. When the div with the BACK text is clicked, the previous div is restored using a slide to the right animation.

You should now have something that looks like this:

sliding panel screenshot

sliding panel screenshot


You can use jsFiddle to play around with the code and once you are happy, you can copy paste the code into your web page.

Happy coding…

Software Development, Web Development

Uncaught TypeError: Object [object Object] has no method ” – jQuery Error

Many developers have been caught up by this error message judging by the number of posts on StackOveflow! I had to fight with this exception for a few hours until the solution popped out to remind me that losing focus is never a good thing!

After having a working prototype, I tried to integrate the FileDrop jQuery plugin to my MVC 4 project. However, as soon as all the files and code was in place, I was greeted by this perplexing error message:

Chrome developer tools 1

This error, in most cases, means that jQuery is not working and no such function can be found or is supported.

At first I thought that it was the bundling of the jQuery files that wasn’t working as expected so I removed the bundles from the page and the _layout.cshtml (master layout page in MVC) and I hardcoded the references to the necessary .js and .css file on the page in question but the problem persisted.

I double and triple checked my Javascript code for typos and un-terminated statements but couldn’t find anything wrong. I moved the code from the js files into the page itself and still no game.

I checked the “Network” tab in Chrome’s Developer’s tools but nothing alarming popped up. This is what my Network traffic as captured during the page load:

Chrome Dev 2


I took a nice break and then returned to my desk to fight this daemon one more time! I loaded the page and looked at the code behind in Developer Tools. Lo and behold the error at the bottom of the page:

In MVC 4, the _layout.cshtml page hides the jquery reference in the footer! As such, I ended up adding it twice to my page and when this happens the browser just barfs out. So if you see this error message again and your issue doesn’t fall into the other categories mentioned above, check for duplicate calls to your js files!

A quick Javascript troubleshooting guide:

  1. Ensure you include all your javascript files in the page that is failing
  2. Ensure that the order of your javascript files is correct. jQuery –> jQuery UI –> anything else
  3. Ensure that there is no typos or syntax errors in your scripts
  4. Ensure that the “<script” tag is closed correctly using </script> and not the /> self-closing format
  5. Ensure that only one copy of the required jQuery/javascript files is pulled on each page.

Happy coding…

.NET, Blog, Software Development, Web Development

HTML5 Drag and Drop file upload with preview using jQuery and MVC 4

With the advent of HTML5 and its wide adoption by all major browsers, web developers now have a new arsenal in their hands for implementing powerful file upload functionality on their website. In this tutorial we will see how to implement this using the FileDrop jQuery plugin  and an MVC controller to receive and store the uploaded files in a repository on the server.

First create a new MVC 4 website in Visual Studio. An existing website can also be used.  Create a new blank view and name it “UploadFiles”. You should be able to navigate to the page using a url similar to this http://localhost:62615/Home/UploadFiles/  Ignore the first part as it will be different on your machine. If you wish, you can add a navigation link on your _layout.cshtml page to make this page more accessible. Next, go to your HomeController and create the following method:

This is the GET method that will allow us to navigate to the UploadFiles view when using the url i mentioned earlier. Now open your View file and edit it in Visual studio. Ensure that the page has a reference to the jquery library either through the _Layout.cshtml page or by directly adding a reference here. The html code required for the plugin is minimal. First, you need to add the libraries that will provide the FileDrop functionality:


Next you need to add a new javascript file under Scripts that will hold the code for the custom FileDrop actions. I named mine  Copy and paste the following code to your javascript file:

Alternatively, you can add the code inside the view using the <scripts></scripts> tags. I like to keep my pages clean hence the separate javascript file. A breakdown of properties that you may want to change is listed below:

  • url: this should point to the controller action that will handle the file uploads
  • paramname: this should be the controller action parameter. The variable name in javascript and your cs file need to match
  • maxFile: maximum number of files allowed to for upload
  • maxFileSize: the maximum size of each file in MBs
  • allowedFileTypes: if left blank then all file types are allowed

The createImage(file) method is used to create a thumbnail for the preview and nothing more.

Finally, go back to your HomeController and add the method that will accept the uploaded files and store them in the filesystem. At this stage, you may choose to perform your image manipulation and change the storage to include a database. For this scenario we will use the file system as our image repository.

The code above will read the list of files and store them one at a time in the TempPath location. TempPath can be any existing directory in your system.

Note that the code will overwrite images with the same name and we never check for valid filenames or if the directory exists .

Downloads: HTML5 DragAndDrop FileUpload

Happy coding….

.NET, Blog, Software Development, Web Development

jQuery UI Autocomplete with jSON in MVC 4

jQueryUi has an autocomplete plugin that allows developers to turn any standard text box to turn any standard textbox to an autocomplete search box. In this case we will try to implement this in the simplest way possible using a web service as the data source.

First of all, create a standard MVC 4 project. This will be used to test our functionality, however any existing website can be used for the same purpose. If you are not already referencing the jQuery and jQuery UI libraries in your _layout.cshtml, add them. You can either add them directly in your code using the old-fashioned way:

Alternatively, if you are like me, you can use the the bundling functionality and create the appropriate bundles and add them using the commands below:

Note that I prefer to bundle my jQuery and jQueryUI together for simplicity but it is totally up to you how you chose to bundle your libraries and css. My BundleConfig.cs class looks like this:

Now you need to add code that implements the autocomplete. First place a label and a text box in the page you wish. In this case, I will go ahead and place it inside index.cshtml

The code above creates a label, a textbox and a button. Ignore the button for now! Next you need to add the necessary code that implements the autocomplete functionality such as search and result parsing. At the bottom of the same page, add the following code segment:

Let’s break this down so that we can see what’s happening:

This code is the key that turns our textbox to an autocomplete text box.

The code above provides the data for our textbox. The source parameter takes a function which in turn performs an ajax query to the url we defined earlier. In this example, the url points to a local WebApi webservice that returns a list of addresses. Upon success, the response object is parsed into an array which populates the drop down with a set of labels and values. The label is what you see in the drop down list and the value can be the same or another value from the returned results. In this case I decided to keep these two values the same, i.e “item”.

The minLength property determines at which stage to kick off the call to the web service. If set to 1 the call will be executed after the first character is typed in the textbox. If set to 3, then the call will be initiated after the 3 character is typed.

The select property allows to execute custom methods. In the example above I chose to display an alert box with the values of the selected option.

As with the select property, the open and close properties allow us to add custom operations when the drop down list box is opened and closed.

This is more or less the code needed to implement a basic autocomplete textbox with webservices as the backend data source. More details about the full plugin documentation can be found here

Happy coding…