Reputation: 2970
Look at the following jquery plugin I have made:
(function($) {
//
// Constructor.
//
var Tb = function(element, options) {
var self = this;
this.options = options;
this.$element = $(element);
this.$input = $(element).find('.tb-input');
this.$label = $(element).find('.tb-label');
this.$element
.proxy('click', this.$input.click)
.proxy('val', this.$input.val);
};
Tb.prototype = {
constructor: Tb
};
//
// jQuery plugin.
//
$.fn.tb = function(option) {
return this.each(function() {
var $this = $(this)
, data = $this.data('tb')
, options = $.extend({}, $.fn.tb.defaults, $this.data(), typeof option == 'object' && option);
if (!data) {
$this.data('tb', (data = new Tb(this, options)));
}
if (typeof(option) == 'string') {
data[option]();
}
});
};
$.fn.tb.defaults = {};
$.fn.tb.Constructor = Tb;
})(window.jQuery);
HTML (demo)
<div id="tb-user-name" class="tb">
<label class="tb-label">This is the placeholder</label>
<input type="text" class="tb-input" />
</div>
javascript init:
$('#tb-user-name').tb();
So basically If I do this:
$('#tb-user-name').val(); // Should return the value of the input not the "container".
$('#tb-user-name').focus(); // Should focus on the input, not the "container"
But my code is not working, how can I do this? I have tried "on" but that doesnt work either, does work on focus with a little work around but "val" is not an event but a function.
UPDATE (Working but hacky)
http://jsfiddle.net/tppiotrowski/WSdmL/3/
Thanks for @teddybeard for this solution, this is however not the best way because this is kinda hacky, and since on EVERY key event the val event gets triggered, I am looking for an alternative, if anyone can help me with that that would be awesome.
Upvotes: 1
Views: 353
Reputation: 2014
Check out this fiddle: http://jsfiddle.net/tppiotrowski/WSdmL/3/
What you are trying to do is override the default focus()
and val()
behavior of jQuery when used on a specific element. Below, I've overridden the val()
and focus()
functions to have special behavior when called by an element with class .tb
:
(function($) {
var originalVal = $.fn.val;
$.fn.val = function(value) {
var self = this;
if (this.hasClass('tb')) self = this.find('.tb-input').first();
if (typeof value == 'undefined') {
return originalVal.call(self);
} else {
return originalVal.call(self, value);
}
};
var originalFocus = $.fn.focus;
$.fn.focus = function(value) {
var self = this;
if (this.hasClass('tb')) self = this.find('.tb-input').first();
if (typeof value == 'undefined') {
return originalFocus.call(self);
} else {
return originalFocus.call(self, value);
}
};
})(jQuery);
Upvotes: 2