i have plugin construction like this:
(function($){
var defaults = {
param1:null,
param2:null
};
var methods = {
init:function(params) {
var options = $.extend({}, defaults, params);
$(this).append('<button class="addbtn">Add elements</button>');
$(document).on('click','.addbtn',function(){
$('body').append(button.html+input.html);
});
}
};
var button = {
html: '<button class="btn">Button</button>'
};
var input = {
html: '<input type="text" class="input" value="" />'
};
var actions ={
clicked:function(){
alert('clicked');
},
hover:function(){
alert('hover');
}
};
$.fn.JPlugin = function(method){
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method"' + method + '" is not found jQuery.mySimplePlugin' );
}
};
})(jQuery);
$('body').JPlugin();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
By clicking on add button you will add input from input.html and button from button.html. How can i initialize click event for input element and button objects from actions.clicked and hover event from actions.hover
You can define events when append button and input.Try following code i hope this helpful.
(function($){
var defaults = {
param1:null,
param2:null
};
var methods = {
init:function(params) {
var options = $.extend({}, defaults, params);
$(this).append('<button class="addbtn">Add elements</button>');
$(document).on('click','.addbtn',function(){
$('body').append(button.html+input.html)
.find(".foo")
.click(function(){actions.clicked($(this))})
.hover(function(){actions.hover($(this))})
});
}
};
var button = {
html: '<button class="btn foo">Button</button>'
};
var input = {
html: '<input type="text" class="input foo" value="" />'
};
var actions ={
clicked:function($this){
console.log($this);
},
hover:function($this){
console.log($this);
}
};
$.fn.JPlugin = function(method){
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method"' + method + '" is not found jQuery.mySimplePlugin' );
}
};
})(jQuery);
$('body').JPlugin();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Related
I am trying to write a jQuery method which watches for changes of inputs inside a given form element:
(function($) {
$.fn.filter = function(options) {
console.log('Outside');
var self = this;
var settings = $.extend({}, options);
this.on('change', ':input', function(e) {
console.log('Inside');
$(self).serialize(); // Here is the problem
});
return this;
}
})(jQuery);
$('#filter-form').filter();
When I use $(self).serialize();, the function being called again. I expect that the 'Outside' part only runs once on initialization and not every time the input of the form changes.
I do not understand what is happening here. I'd appreciate if someone could explain to me why this is happening!
The issue is that you are redefining jQuery's filter method, which it internally uses in its serialize method. If you change the name, it will work. The definition of serialize is shown below:
jQuery.fn.extend( {
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map( function() {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
} )
.filter( function() {
var type = this.type;
// Use .is( ":disabled" ) so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !rcheckableType.test( type ) );
} )
.map( function( _i, elem ) {
var val = jQuery( this ).val();
if ( val == null ) {
return null;
}
if ( Array.isArray( val ) ) {
return jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
} );
}
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
} ).get();
}
} );
Working Example:
(function($) {
$.fn._filter = function(options) {
console.log('Outside');
var self = this;
var settings = $.extend({}, options);
this.on('change', ':input', function(e) {
console.log('Inside');
$(self).serialize();
});
return this;
}
})(jQuery);
$('#filter-form')._filter();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="filter-form">
<input type="text">
</form>
Codepen is here: http://codepen.io/bwolfsohn/pen/jWVZwX
Trying to disable a button via jquery on submit.
I'm simulating an ajax response.
The button is not disabled, but the value on the button is changed to "disabled".
i've tried:
($d).button('disable');
($d).prop( "disabled", true );
where am i going wrong ??
html:
<form class="form-inline bidding" id="rbconfirm" name="IamBidding" action="#">
<input id="arBidAmount_7101" type="text" name="aBidAmount_7101" value="450.00">
<input id="rbbutton" class="btn btn-success" type="submit" value="Bid Now">
jquery/js
$(function () {
var obj2 = {
"arBidAmount_7101" : {
"value" : "500.00"
},
"rbbutton" : {
"disable" : "disabled"
}
};
$("#rbconfirm").submit(function(e){
$.each(obj2, function(i, item) {
var d = i;
var $d = $('#' + i);
if ($d.length !== 0) {
$.each(item,function(i,item) {
if ($d.is(':input')) {
($d).val(item);
}
else if (i=='disable') {
($d).prop( "disabled", true );
}
else if (i=='value') {
($d)[0].innerHTML = item;
}
else{
if (typeof console == "object") {
console.log('notinput '+ i + d);
}
}
});
} else {
if (typeof console == "object") {
console.log(i + 'notfound');
}
}
});
e.preventDefault();
});
});
Here is the corrected javascript...
thanks to #pranin-shakya for the key to the problem..
changing this line:
if ($d.is(':input')) {
to this line:
if (($d.is(':input')) && (!$d.is(':submit')))
to exclude the submit button from being evaluated as an input.
$(function () {
var obj2 = {
"arBidAmount_7101" : {
"value" : "500.00"
},
"rbbutton" : {
"disable" : "true"
}
};
$("#rbconfirm").submit(function(e){
console.log(obj2);
$.each(obj2, function(i, item) {
var d = i;
var $d = $('#' + i);
if ($d.length !== 0) {
$.each(item,function(i,item) {
if (($d.is(':input')) && (!$d.is(':submit')))
{
($d).val(item);
}
else if (i=='disable') {
$($d).prop( "disabled", true );
}
else if (i=='value') {
($d)[0].innerHTML = item;
}
else{
if (typeof console == "object") {
console.log('notinput '+ i + d);
}
}
});
} else {
if (typeof console == "object") {
console.log(i + 'notfound');
}
}
});
e.preventDefault();
});
});
Use:
if ($d.is(':input')) {
($d).val(item);
if (i=='disable') {
$($d).attr( "disabled", "disabled" );
}
}
Your code is not functioning properly as your logic contradicts on line
--if ($d.is(':input')) {--
Since the submit button is also of type INPUT it will return true, the else statement you included
--($d).prop( "disabled", true )-- IS NEVER EXECUTED.
You can use the function addClass.() in jquery (if you use bootstrap)
$("#yourButton").addClass("disable");
Basic Concept
You can do This whitch is preety basic:
$("some sort of selector").prop("disabled", true | false);
If you are using a jQuery UI styled button then it should be enabled / disabled via:
$("some sort of selector").button("enable" | "disable");
Learn more here!
So implementing that in your code:
($d).button('disable');
You can do this:
($d).prop("disabled", true);
Or:
($d).button('disable');
Here is an example
Here is a good code example from stackoverflow!:
$('.rbutton').on('click',function() {
$(this).prop("disabled",true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button class="rbutton">Click me</button>
you can use if/else statement for i after check is(:input)
if ($d.is(':input')) {
$($d).val(item);
if (i=='disable') {
console.log(d);
console.log($d);
// ($d).button('disable');
$d.prop( "disabled", true );
}
if (i=='value') {
//console.log($d);
// console.log( ($d)[0].innerHTML );
$($d)[0].innerHTML = item;
// console.log( ($d)[0].innerHTML );
}
}else{
if (typeof console == "object") {
console.log('notinput '+ i + d);
}
}
Working Demo
Note: you need to work around if/else statements to use it right up to your need
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How would you change this kind of code?
How would I pass these variables in to options through jQuery, so that when the user uses the plugin, they must initialize the plugin from the HTML like so:
<script>
$('.elem').pluginName({
theme: 'blue',
animSpeed: 200
});
</script>
Here's my jQuery code. Pretty messy, but have a look. How could I change the variables to options?
$(function () {
var theme = "sunburst";
var btnColor = "yellow";
var icon = "power";
var message = "Hello World";
var animSpeed = 300;
var animType = 'fadeIn';
var btnText = "Purchase";
var btnLink = 'http://www.google.com';
var closeStyle = "dark";
var content =
'<div id="mn_close" class="' + closeStyle + '"></div>' +
'<div id="mn_border"></div>' +
'<i class="icon-' + icon + '"></i>' +
'<span class="mn_message">' + message + '</span>';
// '' + btnText + '';
$("#mn_close").live("click", function () {
$('.mn_bar').animate({
height: '0'
}, animSpeed, function () {});
});
var mn_bar = $(".mn_bar");
mn_bar.append(content);
$(function () {
mn_bar.addClass("animated");
mn_bar.addClass(animType);
mn_bar.addClass(theme)
});
});
Or here is the jsfiddle. http://jsfiddle.net/LwGRV/6/
I've being trying to implement the code in to this standard type of jQuery code too, but failing to merge:
;(function ( $, window, document, undefined ) {
var pluginName = "defaultPluginName",
defaults = {
propertyName: "value"
};
function Plugin( element, options ) {
this.element = element;
this.options = $.extend( {}, defaults, options );
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function() {
},
yourOtherFunction: function(el, options) {
// some logic
}
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin( this, options ));
}
});
};
})( jQuery, window, document );
Many thanks in advance if anyone can shed some light on to this.
You should have a look at this: http://api.jquery.com/jQuery.extend/
Your variables should be stored within an object.
I'm trying to build a jQuery Plugin using there Name spacing as per there direction here:
http://docs.jquery.com/Plugins/Authoring#Namespacing
Now i have run into a problem my plugin need to use a setTimeout to fire one of its methods,
var jScrollerMethods = {
ready:function(){
return this.each(function(){
var self = this,
$this = $(this),
data = $this.data('jScroller');
settings.timeoutHandle = setTimeout(function(){
if(settings.direction = "left"){
this.moveLeft();
}else if(settings.direction = "right"){
this.moveRight();
}
}, settings.time);
$this.data('jScroller', {
settings: settings,
element: this
});
});
}
$.fn.jScroller = function(call){
if ( jScrollerMethods[call] ) {
return jScrollerMethods[call].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof call === 'object' || ! call ) {
if (call) { $.extend(settings, call); }
return jScrollerMethods.init.apply( this, call );
} else {
$.error( 'Method ' + call + ' does not exist on jQuery.jScroller' );
}
}
but as I though would happen setTimeout is fired from the Window not the plugin object and being that I want the plugin to be usable on more than once per page so I can't just save the current object to the window how can I achieve this?
I found out that when using this outside of the return this.each will give you the exact selector results
So with some work i have managed to do it,
var jScrollerMethods = {
ready:function(){
selector = this;
return this.each(function(){
var self = this,
$this = $(this),
data = $this.data('jScroller');
settings.timeoutHandle = setTimeout(function(){
if(settings.direction = "left"){
selector.jScroller("moveLeft");
}else if(settings.direction = "right"){
selector.jScroller("moveRight");
}
}, settings.time);
$this.data('jScroller', {
settings: settings,
element: this
});
});
}
$.fn.jScroller = function(call){
if ( jScrollerMethods[call] ) {
return jScrollerMethods[call].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof call === 'object' || ! call ) {
if (call) { $.extend(settings, call); }
return jScrollerMethods.init.apply( this, call );
} else {
$.error( 'Method ' + call + ' does not exist on jQuery.jScroller' );
}
}
I got a simple plugin as below:
$.fn.ajaxSubmit = function(options){
var submisable = true;
}
I want to able to change/access the variable myvar from outside the plugin, by doing something like below:
$(function(){
$('form').ajaxSubmit();
$('div').click(function(){
submisable =false;
});
});
You can also create methods to access the variables that are inside a plug in:
$.fn.ajaxSubmit = function(options){
var submisable = true;
$.fn.ajaxSubmit.setSubmissable = function(val){
submisable = val;
}
}
Then you can call it like this.
$('form').ajaxSubmit();
$('form').ajaxSubmit.setSubmissable(false);
This solution is not straight forward, but follows the jquery plugin guidelines.
(function($) {
var myVar = "Hi";
var methods = {
init: function(option) {
return this.each(function() {
$(this).data("test", myVar);
});
},
showMessage: function() {
return this.each(function() {
alert($(this).data("test"));
});
},
setVar: function(msg) {
return this.each(function() {
$(this).data("test", msg);
});
},
doSomething: function() {
//perform your action here
}
}
$.fn.Test = function(method) {
// Method calling logic
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.Test');
}
};
})(jQuery);
$("form").Test("init");
$("#getCol").click(function() {
$("form").Test("setVar", "Hello World").Test("showMessage");
});
Are you thinking to access them as properties? Something like:
$.fn.ajaxSubmit = function(options) {
var defaults = {},
o = $.extend({}, defaults, options);
var _myvar = 'blue'
this.myvar = new function(){
return _myvar;
}
this.setmyvar = function(_input){
_myvar = _input
}
return this.each(function() {
if (_myvar == 'blue') {
alert('hi');
}
if (_myvar == 'red') {
alert('bye');
}
});
}
And set like:
this.setmyvar('red');