views:

140

answers:

1

Does anyone knows how to create a jQuery plugin that will react to the call to val() method?

Here's the scenario:

  1. Take a set of DIVs using jQuery selector and apply a plugin on them (let's say the plugin is called "mytest".
  2. Using the val() method on the same set of DIVs I'd like to set them some properties.

What's the proper way to do this sort of things?

$.fn.example = function(options) {
 return this.each(function() {
  var edits = $("<input type='text'/><input type='text' />");
  $(this).html(edits);
 });
}

$(document).ready(function() {
 $("#example").example();
 $("#example").val("value1 value2");
 window.alert($("#example").val());
});

In this case the first edit should have the value "value1" and the second edit the value "value2". And v.v. by calling the "val()" method I'd like to get the string "value1 value2" back.

Best regards, Matthias

A: 

I've realized that by using additional methods and then calling them using

$("...").pluginname("methodname", ..parameters..);

syntax. It works exactly like other plugins so I guess that's the right way to go. In the case of the example above the code would look like this:

$.widget("ui.example", {
 _init: function() {
 }
});

$.extend($.ui.example, {
 version: "1.7.1",
 defaults: {
  value: ""
 }
});

And then the usage would be:

$("#example").example("option", "value", "value1 value2");
var value = $("#example").example("option", "value");
window.alert(value);
Matthias Hryniszak