Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Monday, May 30, 2011

MVC3, Client Side Validation, and dynamically loaded forms

Recently, I was charged with creating a user edit screen.  The user edit screen was to have 4 different "areas".

1) User Details
2) Actions (disable.. enable)
3) User Roles
4) Audit

We decided to ajax out all the different sections as to make the website more responsive.  If someone disabled an account, all we would have to do is update sections 1 and section 2.  No need to make an expensive call to try and establish all the roles the user has in the system.

The problem I has was that when I loaded the form using jquery get method, the client side validation would not work.  This made it a pain for getting proper error messages back to the client.  I didn't want to have to parse a result and start using my javascript skillz to display messages all over the place.  In fact, the built-in client side validation "features" that MVC3 provides are quite nice.  You define validator logic in one place and go from there....

In any event, the point is, when you dynamically load a form, the client side validation does not work out of the bat. To answer why, we have to look at the jquery.validate.unobtrusive.js libraries that MS provided for us. 


$(function () {
        $jQval.unobtrusive.parse(document);
    });

Great piece of code.  The problem is, this only runs once... when the original document is loaded (unless you include all of your JS again in the AJAX layout you are using.. but that would be a lot of duplication). 

The solution is quite simple.  All you have to do is add a call to the parsing mechanism with the jquery selector for the form you wish to validate.

$.get(
                '@Url.Action("GetPersonalData")',
                {
                    Id: currentUserId
                },
                function (data) {
                    $("#personal").html(data);
                    $.validator.unobtrusive.parse("#personal form:first");
                    ... continue ...

Voila, you will now have client side validation on your dynamically loaded form.

Update:
If you want this form to submit via an ajax post (using jquery natively) you have to determine if the form is valid first.  You can find out more here.


References:
http://stackoverflow.com/questions/4406291/jquery-validate-unobtrusive-not-working-with-dynamic-injected-elements
http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

Saturday, March 5, 2011

Checkbox-fu with JQuery

The current project that I am is a .net MVC 3 project.  The framework comes with the JQuery library for making client side controls easier to create.  I have only used YUI (2) before, so the concept of a javascript library is not uncommon to me.

I must say that I am really liking the JQuery library.  As with all libraries, it takes a bit to learn the in's and out's of how the library works.  In this post, I am going to show you how to create buttons that will check and uncheck all of the checkboxes on the page.

First of all, the code.
$(document).ready(function()
   {
    $("#all").click(function() {
     $(".checkboxes input:checkbox").each(function(){
               $(this).attr('checked','true');
               });
    }); // end all.click
    
    $("#none").click(function() {
     $(".checkboxes input:checkbox").each(function(){
               $(this).removeAttr('checked');
               });
    });
   });

Soccer
Hockey
Football
Basketball







If you view the source of this page, you should see the html mark up that I have up above.  It is pretty simple.  I have a div with a class of checkboxes.  Inside that are 4 checkboxes that are currently unchecked.  I then have a span with 2 buttons in it (a select all, and a clear).

The Javascript code itself is pretty easy (as is most things with JQuery).  Since I want my buttons to have functionality provided by the javascript, I need to ensure that my javascript runs after the elements that they affect load.  The easiest way to do this is to wrap all the javascript code in a document.ready block.  JQuery uses the $(document).ready function to accomplish this.

JQuery works on the idea of selectors.  You can use attributes such as id and class to act as selectors.  You can also use keywords such as form to accomplish the same thing.  Be careful if you have more than one form on your page.

Back to the code.  My buttons have an id of all or none respectively.  The line inside the function uses the JQuery selector methods to select multiple html elements.  In this case, it is looking inside any divs with the .checkboxes class.  From that, it will look for any input elements of type checkbox.  The .each method allows you to perform a function on each element in the array that is returned from the JQuery selector method.

The "this" keyword is pretty self explanatory in this case.  It clearly represents the DOM object that I am functioning on.  This is because I have called it form a .each method.  See http://remysharp.com/2007/04/12/jquerys-this-demystified/ for more information on the "this" keyword in JQuery.

The last piece of the puzzle is the attr and removeAttr methods.  Basically, this adds an attribute to the DOM object, or removes it.  These are handy methods if you want to quickly disable and re-enable buttons.  In the above case, I am using it to add the checked and remove the checked attribute.

JQuery can do a lot more than this, but this small example gives a small glimps of how powerful the framework is.  You can easily accomplish several tasks with just a couple lines of code.