I have this jquery code to check for any value on a given input and then add a simple class if the input has a value.
But in console i receive error that .val() is not a function?
my code is:
$.fn.tkFormControlMaterial = function(){
this
.blur(function () {
if (this.val())
this.addClass('used');
else
this.removeClass('used');
})
.after('<span class="ma-form-highlight"></span><span class="ma-form-bar"></span>');
};
bind will set you free
$.fn.tkFormControlMaterial = function(){
this
.blur(function () {
if (this.val())
this.addClass('used');
else
this.removeClass('used');
}.bind(this))
.after('<span class="ma-form-highlight"></span><span class="ma-form-bar"></span>');
}.bind(this);
I found the solution.
If anyone needs a working sample of my own code above:
$.fn.tkFormControlMaterial = function(){
$(this)
.blur(function () {
if ($(this).val())
$(this).addClass('used');
else
$(this).removeClass('used');
})
.after('<span class="ma-form-highlight"></span><span class="ma-form-bar"></span>');
};
You could also try to use the "self" pattern.
var _self = this;
$.fn.tkFormControlMaterial = function(){
_self
.blur(function () {
if (_self.val())
_self.addClass('used');
else
_self.removeClass('used');
})
.after('<span class="ma-form-highlight"></span><span class="ma-form-bar"></span>');
};
Related
I have implemented several jQuery plugins for my current project.
Since some plugins have functions with the same name, the one called in the last one defined.
Here is the definition of my first plugin:
$(function($)
{
$.fn.initPlugin1 = function(parameters)
{
var defaultParameters = {};
$(this).data('parameters', $.extend(defaultParameters, parameters));
return $(this);
};
$.fn.function1 = function(){ console.log('Function 1.'); };
$.fn.callFunction = function(){ $(this).function1(); };
});
And here is the definition of my second plugin:
$(function($)
{
$.fn.initPlugin2 = function(parameters)
{
var defaultParameters = {};
$(this).data('parameters', $.extend(defaultParameters, parameters));
return $(this);
};
$.fn.function2 = function(){ console.log('Function 2.'); };
$.fn.callFunction = function(){ $(this).function2(); };
});
I have also this scenario :
$("#div1").initPlugin1().callFunction();
$("#div2").initPlugin2().callFunction();
For this specific scenario the consoles shows: Function 2. Function 2.
In fact, since the callFunction() is also defined in the second plugin, this is the one used.
I would like some advise on what is the best way to solve this problem.
Is it possible to create a thing similiar to a namespace ?
Thank to #syms answer, I have created the following example.
Plugin1:
$(function($) {
$.fn.initPlugin1 = function() {
console.log('Initialized Plugin1');
return $(this);
};
$.fn.initPlugin1.testFunction = function() {
$(this).append('Function 1.');
};
});
Plugin2:
$(function($) {
$.fn.initPlugin2 = function() {
console.log('Initialized Plugin2');
return $(this);
};
$.fn.initPlugin2.testFunction = function() {
$(this).append('Function 2.');
};
});
Main:
(function($)
{
$(document).ready(
function()
{
$("#div1").initPlugin1(); //Run correctly
$("#div2").initPlugin2(); //Run correctly
$("#div1").initPlugin1.testFunction(); //Fail
$("#div2").initPlugin2.testFunction(); //Fail
});
})(jQuery);
When I run my code, I got the following error: Cannot read property 'createDocumentFragment' of null.
Apparently, the this object is corrupted.
you can try this,
$(function($) {
$.fn.initPlugin1 = function() {
console.log('Initialized Plugin1');
return $(this);
};
});
$(function($) {
$.fn.initPlugin2 = function() {
console.log('Initialized Plugin2');
return $(this);
};
$.fn.callFunction = function(param) {
$(this).append(param);
};
});
(function($) {
$(document).ready(
function() {
$("#div1").initPlugin1(); //Run correctly
$("#div2").initPlugin2(); //Run correctly
$("#div1").initPlugin1().callFunction('function1');
$("#div2").initPlugin2().callFunction('function2');
});
})(jQuery);
We all know that use the val() will not trigger the change event, so we also use .trigger('change') behind the val().
But the problem is that someone write the val() did't with trigger() and it's a external file that I can't edit it.
So, how can I detect value change through some code same like below:
$('.elem').on('change', function(){
// do something
});
My suggestion is to override jquery's val()
var originalValFn = jQuery.fn.val;
jQuery.fn.val = function() {
this.trigger('change');
originalValFn.apply( this, arguments );
}
jsfiddle: http://jsfiddle.net/2L7hohjz/js
var originalValFn = jQuery.fn.val;
function getErrorObject(){
try { throw Error('') } catch(err) { return err; }
}
jQuery.fn.val = function() {
if ($(this).hasClass( "element" )) {
var err = getErrorObject();
var caller_line = err.stack.split("\n")[4];
var index = caller_line.indexOf("at ");
var clean = caller_line.slice(index+2, caller_line.length);
console.log(clean);
console.log(arguments);
}
originalValFn.apply( this, arguments );
};
Try:
setTimeout(function() {
if (currentValue != previousValue)
{
// do something
}
}, 500);
Thank you,
I commonly use the solution from this post to get around problems like this one:
hidden input change event
watchField('.elem', function(){
//do some stuff here
});
function watchField(selector, callback) {
var input = $(selector);
var oldvalue = input.val();
setInterval(function(){
if (input.val()!=oldvalue){
oldvalue = input.val();
callback();
}
}, 100);
}
Try:
$('.elem').on('keyUp', function(){
// do something
});
or
$('.elem').on('lostFocus', function(){
// do something
});
Thank you,
I am attempting to perform some action on the foucsin of the textbox. However, for some reason the event never fires.
$(".ddlAddListinTo li").click(function () {
var urlstring = "../ActionTypes";
$.post(urlstring, function (data) {
$(window.open(urlstring, 'Contacts', 'width=750, height=400')).load(function (e) {
// Here "this" will be the pop up window.
$(this.document).find('#txtAutocompleteContact').on({
'focusin': function (event) {
alert('You are inside the Contact text box of the Contacts Popup');
}
});
});
});
});
When doing it that way, you generally have to find the body or use contents() to access the contents, as in
$(this.document).contents().find('#txtAutocompleteContact')
but in this case using a little plain javascript seems more appropriate :
$(".ddlAddListinTo li").on('click', function () {
var urlstring = "../ActionTypes";
$.post(urlstring, function (data) {
var wind = window.open(urlstring, 'Contacts', 'width=750, height=400');
wind.onload = function() {
var elem = this.document.getElementById('txtAutocompleteContact');
$(elem).on('focus', function() {
alert('You are inside the Contact text box of the Contacts Popup');
});
}
});
});
I've got following solution to prevent of multiple clicks (respect only the first one and ignore the rest):
preventMultiClick = function() {
$(this).unbind("click");
$(this).bind("click", function() {
return false;
});
};
preventMultiSubmit = function() {
$(this).unbind("submit");
$(this).bind("submit", function() {
return false;
});
};
$("a").one("click", preventMultiClick);
$("#user").one("submit", preventMultiSubmit);
That solution for me is not elegant I think should be. So I tried upgrade it to following one:
preventMultiClick = function(event) {
$(this).unbind(event);
$(this).bind(event, function() {
return false;
});
};
$("a").one("click", preventMultiClick("click"));
$("#user").one("submit", preventMultiClick("submit"));
and that solution doesn't work. Could somebody explain why or tell me how the function respecting event given as function argument should be written?
The issue is you are calling the function when you are binding the handler, event object is passed to your handler, also event is an object, you should use it's type property.
var preventMultiClick = function(event) {
$(this).unbind(event.type);
$(this).bind(event.type, function() {
return false;
});
};
$("a").one("click", preventMultiClick);
$("#user").one("submit", preventMultiClick);
The problem is that you're passing in an undefined variable rather than the function reference. Instead I would do something like this.
preventMultiClick = function(event) {
$(this).unbind(event.type);
$(this).bind(event.type, function() {
return false;
});
};
$('a').one('click', preventMultiClick);
$('#user').one('submit', preventMultiClick);
Each event contains it's type.
I have two functions click and live. I want to pass a parameter from click to live.I tried something like below but it's not working.
jQuery(document).ready(function(){
var test = 'test' ;
jQuery('.item a').click(test);//pass an argument from here
});
jQuery('.item a').live('click',function(e,test) {
alert(test);//access argument here
});
Is this possible?
Update:
function init() {
//When you click on a link
jQuery('.item a').live('click',function(e,test) {
alert(test);
});
}
jQuery(document).ready(init);
jQuery(document).ready(function(){
var test= 'test';
jQuery('.item a').trigger('click', test);
});
I am expecting an alert.
Edit2:
jQuery(document).ready(function(){
(function($){
$('.item').each(function() {
$(this)[0].oncontextmenu = function() { return false }
});
$.fn.ctrl = function(key, callback) {
if(typeof key != 'object') key = [key];
callback = callback || function(){ return false; }
return $(this).keydown(function(e) {
var ret = true;
$.each(key,function(i,k){
if(e.keyCode == k.toUpperCase().charCodeAt(0) && e.ctrlKey) {
ret = callback(e);
}
});
return ret;
});
};
$.fn.disableSelection = function() {
$(window).ctrl(['a','s','c']);
return this.each(function() {
$(this).attr('unselectable', 'on')
.css({'-moz-user-select':'none',
'-o-user-select':'none',
'-khtml-user-select':'none',
'-webkit-user-select':'none',
'-ms-user-select':'none',
'user-select':'none'})
.each(function() {
$(this).attr('unselectable','on')
.bind('selectstart',function(){ return false; });
});
});
};
$('.item').disableSelection();
})(jQuery);
});
Thanks.
You can use trigger() instead, which allows you to pass arguments;
jQuery(document).ready(function(){
var test = 'test' ;
jQuery('.item a').trigger('click', test); //pass an argument from here
});
jQuery('.item a').live('click',function(e,test) {
alert(test);//access argument here
});
Or You can use hidden field to store params need to pass then read it in click function
jQuery(document).ready(function(){
var test = 'test' ;
jQuery('#hiddenID').val(test);
jQuery('.item a').click(test);//pass an argument from here
});
jQuery('.item a').live('click',function(e,test) {
var test = jQuery('#hiddenID').val();
alert(test);//access argument here
});
You can also try this
jQuery(document).ready(function(){
var test = 'test' ;
$('.item a').trigger({type:'click', myParam:test}); // pass the event object with param
});
$('.item a').live('click',function(e) {
alert(e.myParam); //access param here
});
Also remember live is deprecated instead use on.
Update:
jQuery(document).ready(function(){
var test= 'test';
$('.item a').trigger({type:'click', myParam:test});
});
$('.item a').live('click',function(e) {
alert(e.myParam); //access param here
});