How to Enhance Forms Using jQuery UI

Step 2

jQuery UI plugin has several advantages over a custom js code and we can keep functions private by using _. init function is first called by a jQuery UI plugin when it is invoked, so we will code our js code in the init function.

$.widget("ui.form",{
		  _init:function(){
           //our code here
          }
		 });

Step 3

Now we will initialize some variables and add basic theming to the form.

$.widget("ui.form",{
		  _init:function(){
             var object = this;
			 var form = object.element;
			 var inputs = form.find("input , select ,textarea");

			  form.find("fieldset").addClass("ui-widget-content");
			  form.find("legend").addClass("ui-widget-header ui-corner-all");
			  form.addClass("ui-widget");

          }

		 });

Here we have got the reference of the form widget in the object variable. The reference of the element invoking the plugin is stored in the element variable of the object. Then we have collected form elements in the inputs.

After that we have themed the form using jQuery UI’s inbuilt classes. The role of widget classes have been discussed earlier and assuming that the form contains fieldset and legend which it should, we have added widget content to fieldset since it contains the elements and header to the legend.

Note: Unlike a jQuery plugin where ‘this’ refers to the current object, in jQuery UI plugin this refers to the instance of the plugin.

Pages: 1 2 3 4 5 6 7 8 9 10 11 12

This entry was posted on Monday, April 5th, 2010 at 19:05 and is filed under Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Hi, I am Abhin from beautiful city of lakes Udaipur, India. When it comes to work, I have an obsessive compulsive disorder to do everything I find and most of the time, I end up doing nothing ;). UI/UE fascinates me.

About the author Published by Abhin

42 Responses »

  1. It certainly makes pretty forms but I notice that your example is lacking any label elements. Labels are used to link the captions to the fields, much like those on your comment form. I much prefer clicking on a checkbox’s label to the checkbox itself. So my question is… does the jQuery UI still work correctly with labels in place? For example, is it able to check the checkboxes by clicking on the label?

  2. That is a very well written tutorial, thanks!

  3. @PhillS Hi, our main aim is create a jQuery UI plugin, Its really upto the user to use labels or not… a plugin has to provide maximum flexibility… If you want to add labels if can be done by binding label with the proxy element 🙂

  4. What’s the use of a captcha, since automated bots don’t have Javascript enabled?

  5. You should check out your live demo in IE7/8.

    Looks great in Firefox though!

  6. @Mike yes… CSS3 rounded corners is not supported in IE, but you can overcome them using DD_roundies, @Diti u can use a simple php validation at server… the main aim of this article was to make forms pretty. But nice point 🙂

  7. the background of the textarea is visually split into two parts? That looks little bit ugly?
    Do you have a fix for that?

  8. hello,

    nice tutorial.
    Are you sure with the use of the ui-state classes?
    The UI Framework doc says that it should be applied on:
    “Class to be applied to clickable button-like elements”

    input fields and textareas primary are not clickable button-like elements?
    In the end, you use ui-classes, but the implementation will not be constistant with other widgets, because the classes are not designed for input, and textarea elements?

    For input and textarea you should use ui-widget-content-
    For buttons you should use the ui. .button() method.

    What do you think?

  9. @rooki to answer your questions –
    1) u can change the ui change of textarea, if u dont like its appearance. jQuery UI means you can create your own theme to the granular level (Themeroller).
    2) Yes, I knw they stated that it should be applied on button like elements, but they had given a brief description of where to use these classes not compulsory rule to adhere to them. Even filament group uses jQueryUI state classes in different ways, The autocomplete widget uses state classes and its not a button.

  10. Hi Abhin,

    thank you for the answer.
    is there something broken with the radio function?
    on the demo page, you can select all readios together !?

  11. hi Rooki,
    I didn’t added the same name to the radio buttons, thats why u r able to select all of them,

  12. Hi rooki
    Yes this is only a Tutorial and can not be used immediately
    It only tell you HOW to do it. the checkbox and the radio is replaced by the span and there are no addtional binding on them.

  13. Very nice work!
    The problem with radio remains. All of them can be checked even on same name.
    Also, the HIDDEN fields are wrapped in LABEL tag.
    Regards

  14. very well written and nicely explained tutorial..I am new to jQuery and this article has helped me a lot..

  15. Very nice.
    But !! Unlike a regular select box, it doesn’t close the list when you select one of the options, it waits for you to click on arrow on right.

    Also when you put multiple select boxes it mixes all of their values. (select item 1 is showing the select item 2’s value when you change select item 2)

    Any fix for those ?

    • To fix this issues, I do the following :

      Replace line 149 into main.js :

      parent.append("");

      By

      parent.append("");

      Replace lines 156-159 by this :

      $(parent).next("ul").find("li").click(function() {
      $(parent).children('span').first().html($(this).html());
      $(element).val($(this).html());
      $(parent).next().slideToggle('fast');
      });

      Now the select box works even if there is more than one instance on the page (no longer used a unique id) and the click event on a item close it.

      Hope this help.
      Marc.

  16. Hu hu, some problems when I paste the code into my previous comment.

    So i have uploaded a complete version here of the modified file.
    The modified lines are highlighted.
    Now the select box works even if there is more than one instance on the page (no longer use a unique id) and the click event on a item close it.

    Hope this help.
    Marc.

  17. Hi,
    This is another way for highlight html page contents, we will use the power of JQuery. It works on IE,Opera,FireFox & Safari Browsers

    Please read the Article Here:
    http://sevenadoo.com/Articles/JavaScript-d4/Using-JQuery-to-select-and-Highlight-HTML-Contents-c2.aspx

  18. Absolutely no keyboard support, not even selectable with tab…

    • @Phazei maybe try showing the creator a little more respect than that…

      Some people (like me) were just pleased to have such an awesome script to build from 🙂

      Anyway, i coded in some of the functions you complained about. Not because of you, because i needed it anyway.

      You can find the version with keyboard support here —>>http://pastebin.com/0zRRTemX

      I also tweaked a couple of other things.

      Like……

      [*]Checkbox Not getting checking if it is already checked when the form is loaded.

      [*]Select If there is a default value set it wouldnt set it in the new fancy select

      I fixed them both in my version.

      @The creator Fantastic work, thank you its very handy for dynamic content 😀

  19. UI Looks nice, but when I click on Reset Button, Select, Checkbox, Radio box are not reset in the UI look and feel. This throws me off…

  20. hi you guys, I was just checkin’ out this site and I really love the foundation of the article, and have nothing to do, so if anyone would like to to have an enjoyable convo about it, please contact me on skype, my name is kevin kowalsky

  21. I’m impressed with your jquery skills. Are you able to do freelance development. I have a small project in mind. Please drop me a note at ipserv@yahoo.com with your prefessioanl services rate.

    -Auro

  22. Any suggestions how to implement this when I have to forms on my website, but only want to have the captcha on one of the forms?

    • The best way would be to edit it to allow for options to be passed to it.

      $(‘#form1’).form({‘showCaptia’: false});
      $(‘#form2’).form();

  23. Nice, Thanks.
    since jquery 1.4 the line $(element).val($(this).html()); is invalid – select by text does not work anymore.
    I have fixed it like that:
    var selectedText=$(this).html();
    $(element).find(“option”).each(function(){
    if (selectedText==$(this).text())
    {
    $(this).attr(“selected”, true);
    }
    else {
    $(this).attr(“selected”, false);
    }
    });

  24. This is great!. but you guys already find out the solution to Radio Button yet? Someone above me also has such problem like me.

    • I changed the code for handling radio’s with the code below:
      Please not that I do not wrap the UI elements with a label (I want to do that my self in my forms) but wrap with a element.


      radio:function(element){
      $(element).parent("span").after("");
      var parent = $(element).parent("span").next();
      $(element).addClass("ui-helper-hidden");
      $(element).change(function(){
      var group_name = $(this).attr("name");
      //alert(group_name);
      $("input:radio[name="+group_name+"]").each(function(){
      var ui_elem = $(this).parent().next().children(":first");
      if( $(this).attr("checked") || $(this).attr("checked") == "checked" )
      $(ui_elem).addClass("ui-icon-bullet").removeClass("ui-icon-radio-off").parent().addClass("ui-state-active");
      else
      $(ui_elem).addClass("ui-icon-radio-off").removeClass("ui-icon-bullet ui-state-active").parent().removeClass("ui-state-active");;
      });
      });

      parent.addClass("ui-icon ui-icon-radio-off");
      parent.wrap("");

      parent.parent().addClass('hover');

      parent.parent("span").click(function(event){
      // $(this).toggleClass("ui-state-active");
      // parent.toggleClass("ui-icon-radio-off ui-icon-bullet");
      $(element).click();

      });
      },

  25. Submit buttons don`t work in this example why ?

  26. You shouldn’t do all that within the _init: it should be in the _create:.
    _init fires every time you do $(‘form’).form();
    However _create only fires the first time that you do $(‘form’).form();

    Also you are running your selectors too much cache your variables or at least chain them.
    For example you have this in the code
    $.each(inputs,function(){
    $(this).addClass(‘ui-state-default ui-corner-all’);
    $(this).wrap(“”);

    it should be something like this.
    $.each(inputs,function(){
    var $this = $(this)
    .addClass(‘ui-state-default ui-corner-all’);
    .wrap(“”);

    Then further down in this same loop you can just refer to $this instead of haveing to call $(this) over and over. With all the instance that you do this it could start to add upto quite an over head on a large form if you fixed everywhere that you are doing this type of thing.

Trackbacks

  1. designfloat.com
  2. Tweets that mention Enhancing Forms using jQuery UI | TutToaster -- Topsy.com