JQuery plugin that takes and returns a value using the val () method

Does anyone know how to create a jQuery plugin that will respond when the val () method is called?

Here's the script:

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

What's the correct way to do this kind of thing?

$.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 change the value "value2". And vv calling the "val ()" method, I would like to return the string "value1 value2".

Regards, Matthias

+1


a source to share


1 answer


I figured out that by using additional methods and then calling them with

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

      

syntax. It works exactly the same way as other plugins, so I think that's the right way. In the case of the example above, the code will 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);

      

0


a source







All Articles