Reputation: 23
I am trying to write a simple jquery plugin where in - it will have a textarea or textbox and some button.
On clicking the button I need to get the value of the relevant textarea or textbox.
I have written some code, but I am stuck at a point. Can anyone help me with this?
Here is the Fiddle: http://jsfiddle.net/655wz/
(function ($) {
$.fn.widgetify = function (options) {
var defaults = {
multi: false
};
var settings = $.extend({}, defaults, options);
return this.each(function () {
//create all dom elements here
this.template = $("<div class='outer' id='" + settings.id + "'>Sample Class</div>");
this.textbox = $("<input type='text' name='sample' id='sample' />");
this.textarea = $("<textarea name='sampletextarea' id='sampletextarea'></textarea>");
this.go = $("<input type='button' name='" + settings.id + "_go' id='" + settings.id + "_go' value='Go' />");
//append all dom elements here
if (settings.multi) {
$(this.template).append(this.textarea);
} else {
$(this.template).append(this.textbox);
}
$(this.template).append(this.go);
$(this).append(this.template);
//all events stuff here
this.go.on('click', $.proxy(function () {
//use original 'this'
alert($(this.textarea).val());
}, this));
return this;
});
}
}(jQuery));
Upvotes: 2
Views: 111
Reputation: 3735
First, you have bind you plugin twice with "#example-widget-container"
, thats why you are not getting the correcr output.
Second, You already have dom textarea and dom textbox so need not to do
alert($(this.textarea).val());
instead
this.go.on('click', $.proxy(function () {
//use original 'this'
if (settings.multi) {
alert(this.textarea.val());
} else {
alert(this.textbox.val());
}
}, this));
would work.
See demo here
Upvotes: 0
Reputation: 922
there is two problems, first you must add the id in all the inputs
this.textbox = $("<input type='text' name='sample" + settings.id + "' id='sample" + settings.id + "' />");
this.textarea = $("<textarea name='sampletextarea" + settings.id + "' id='sampletextarea" + settings.id + "'></textarea>");
and second you must check your multi boolean
if (settings.multi) {
alert($(this.textarea).val());
} else {
alert($(this.textbox).val());
}
Upvotes: 0
Reputation: 6740
I've found two reasons.
A) As prevously mentioned my uchamp about the ID. You should change it in HTML and JS.
B) On Go.click
function you have only called
alert($(this.textarea).val());
So, Now text area is working fine, Textbox will not work. You may want to add
alert($(this.textbox).val());
to make it work.
Upvotes: 0
Reputation: 2512
You need to fix your html and not repeat your div id. Change the second div to:
<div id="example-widget-container1"></div>
The rest of the code looks fine. At least as far as the example goes.
Also, in your click handler you would have to alert textarea and textbox values depending upon your settings.multi variable.
Upvotes: 5