Reputation: 15358
Fairly basic question i'm hoping. In the following javascript, I want to run the checkval() function as if it were executed in the scope of which "this" (within the checkval) refers to the element that the plugin is being called on (well, one of the elements).
So if i called
$('.has_hidden').conditional();
Then that would run the checkval on all those items as well as binding it to the on change event.
Reason is, I have a form, which will unhide further options if you type in something, say if you type in "australia" it will unhide a bunch of other elements. Now when I save and reload that form, my php script repopulates the data, but the other elements remain hidden. I just need to run check val so they get un hidden. Ming Bai Ma
/**
* This class will show or hide a bunch of elements (A,B,C) based on the value in element (E, this).
* To use it, take the name of the form element (E, this) and apply it as a class to A,B,C
* Then add a display none to A,B,C (add class off)
* Set the "rel" tag on
* Finally, run $(E).conditional();
*/
(function( $ ){
$.fn.conditional = function() {
return this.each(function(){
var $this = $(this);
$this.unbind('change.cns').bind('change.cns', checkval);
});
function checkval(){
var regex = $(this).attr('rel');
var class_name =$(this).attr('name');
if($(this).val().search(regex)>-1)
$('.'+class_name).show();
else
$('.'+class_name).hide();
}
};
})( jQuery );
Upvotes: 1
Views: 226
Reputation: 15358
Sorry I didn't explain my question properly, but what I was actually looking for was
$this.trigger('change.cns');
Upvotes: 0
Reputation: 6312
I think you can use the jquery proxy in this case to solve this issue:
$this.unbind('change.cns').bind('change.cns', checkval);
To
$this.unbind('change.cns').bind('change.cns', $.proxy( checkval, $this ));
Upvotes: 1