I have some forms and I would like to add classes to the elements. Here is an example:
<form ... id="test1"> </form>
<form ... id="test2"> </form>
I found the following but I don’t understand the syntax of the first few lines
(function ($) {
$.widget("ui.format", {
_init: function () {
var self = this; //the plugin object
var o = self.options; //user options
//get all form elements
var form = self.element; //the form that reformed was called on
var fieldsets = form.find('fieldset');
var legends = form.find('legend');
var text_inputs = form.find('input[type="text"] , input[type="password"] , textarea');
var checkboxes = form.find('input[type="checkbox"]');
var radios = form.find('input[type="radio"]');
var buttons = form.find('input[type="reset"] , input[type="submit"], button');
//add appropraite styles to form elements
form.addClass('ui-widget');
fieldsets.addClass('ui-widget ui-widget-content ui-corner-all');
legends.addClass('ui-widget ui-widget-header ui-corner-all');
text_inputs.addClass('ui-widget ui-widget-content ui-corner-all');
}); //end plugin
})(jQuery);
In particular I don’t understand this:
(function ($) {
$.widget("ui.format", {
_init: function () {
and the last line:
})(jQuery);
Can someone explain to me what it means and step me through just these three lines.
For example:
- What does the _init mean
- Can I use mixed case for “ui.format” and is this the name of the function?
- What’s the .widget mean, how could I apply this code to my form? I assume I would need to call it somehow from inside my document ready and then attach it to a particular form id.
- Also what happens if I apply this to my form and then later on apply it again. Will it add the same classes twice?
The
(function ($) {starts off a pattern that is commonly used with jQuery plugins (and many other JavaScript functions). The entire pattern is:Wrapping the whole thing in parentheses makes it execute as soon as it loads (i.e., before the DOM is ready).
The
$.widget("ui.format", {begins to extend the jQuery widget factory passing in ‘ui.format’ as the “namespace.widgetname” and then the{starts the object to pass in.“what does the _init mean”:
_init: function() {is a function called “_init” that is being defined in the object passed in to the widget factory.“can I use mixed case for “ui.format””: No, as it’s the namespaced widget that is being modified and JavaScript is case-sensitive.
As far as applying this to your code, I haven’t seen this plugin before so I’ll have to refer you to the documentation on the site where you got it.
In general, you apply jQuery widgets by passing a selector to the jQuery object and calling the widget (i.e.,
$('form#test1').ui.widget();).You can also add classes with the
.addClass()function.