I want to learn how to write Jquery plugin.This is my normal function and convert it into jquery plugin could you suggest me how to do this.
So that I can easily understand how to convert function to the plugin.
function probe_Validity(element) {
var validate = true;
$(".required-label").remove();
var warnings = {
text: "Please enter Name"
};
element.find(".required").each(function() {
var form_Data = $(this);
if (form_Data.prop("type").toLowerCase() === 'text' && form_Data.val() === '') {
form_Data.after('<div class="required-label">' + warnings.text + '</div>').addClass('required-active');
validate = false;
}
if (validate) {
return true;
} else {
return false;
}
$(function() {
$(".required").on("focus click", function() {
$(this).removeClass('required-active');
$(this).next().remove();
});
});
});
}
Take a look at this project jQuery plugin boilerplate
Consider this as a base plugin definition, look it up, follow the steps and adjust them to your needs.
It's quite easy to do you just use
jQuery.fn.theNameOfYourFunction = function() {}
then you can get the element the function is called on like this :
var element = $(this[0])
so with your function it would be :
jQuery.fn.probe_Validity = function() {
var element = $(this[0]);
var validate = true;
$(".required-label").remove();
var warnings = {
text: "Please enter Name"
};
element.find(".required").each(function() {
var form_Data = $(this);
if (form_Data.prop("type").toLowerCase() === 'text' && form_Data.val() === '') {
form_Data.after('<div class="required-label">' + warnings.text + '</div>').addClass('required-active');
validate = false;
}
if (validate) {
return true;
} else {
return false;
}
$(function() {
$(".required").on("focus click", function() {
$(this).removeClass('required-active');
$(this).next().remove();
});
});
});
};
this can be called like so :
$('#id').probe_Validity ()
I looking for some pointer on how data is sent using a custom library that connects to a java server running as a websocket server.
The code im using to connect which is successful
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="b4j_ws.js"></script>
<script>
// connection to websocket
$( document ).ready(function() {
b4j_connect("/push/ws");
});
</script>
and this is my guess and how to send data using the library which at the moment is not correct, the message would be 'wwww' when sent successfully.
<script>
b4j_ws.send(JSON.stringify({"type":"data","data":"wwww"}));
</script>
These are frames i captured from the working example but it used a button where i want to just use jquery
{"type":"event","event":"btnsend_click","params":{"which":1,"target":"btnsend","pageX":31,"pageY":19,"metaKey":false}}
{"id":"#txt","method":"val","etype":"runmethodWithResult"}
{"type":"data","data":"wwww"}
the library which is b4j_ws.js in the above code.
//B4J WebSockets client library v0.9
/*jslint browser: true*/
/*global $, jQuery, WebSocket*/
/*jshint curly: false */
"use strict";
var b4j_ws;
var b4j_closeMessage = false;
//only called as a result of a server request that is waiting for result.
//this method should not be called in any other case.
function b4j_sendData(data) {
b4j_ws.send(JSON.stringify({type: "data", data: data}));
}
function b4j_raiseEvent(eventName, parameters) {
try {
if (b4j_ws.readyState !== 1) {
if (b4j_closeMessage === false) {
window.console.error("connection is closed.");
window.alert("Connection is closed. Please refresh the page to reconnect.");
b4j_closeMessage = true;
}
} else {
b4j_ws.send(JSON.stringify({type: "event", event: eventName, params: parameters}));
}
} catch (e) {
window.console.error(e);
}
}
function b4j_addEvent(selector, event, eventName, preventDefault) {
var obj = $(selector);
if (obj.length > 0) {
obj.on(event, function (e) {
if (preventDefault) {
e.preventDefault();
e.stopPropagation();
}
b4j_raiseEvent(eventName, {which: e.which, target: e.target.id, pageX: e.pageX, pageY: e.pageY, metaKey: e.metaKey});
});
}
}
function b4j_addAutomaticEvents(data) {
$.each(data, function (index, value) {
b4j_addEvent("#" + value.id, value.event, value.id + "_" + value.event, true);
});
}
function b4j_runFunction(func, params) {
return window[func].apply(null, params);
}
function b4j_eval(params, script) {
var f = new Function(script);
return f.apply(null, params);
}
function b4j_connect(absolutePath) {
if (typeof WebSocket === 'undefined') {
window.alert("WebSockets are not supported by your browser.");
return;
}
var l = window.location, fullpath;
fullpath = ((l.protocol === "https:") ? "wss://" : "ws://") + l.hostname + ":" + l.port + absolutePath;
b4j_ws = new WebSocket(fullpath);
b4j_ws.onmessage = function (event) {
var ed = JSON.parse(event.data);
if (ed.etype === "runmethod") {
$(ed.id)[ed.method].apply($(ed.id), ed.params);
} else if (ed.etype === "runmethodWithResult") {
b4j_sendData($(ed.id)[ed.method].apply($(ed.id), ed.params));
} else if (ed.etype === "setAutomaticEvents") {
b4j_addAutomaticEvents(ed.data);
} else if (ed.etype === "runFunction") {
b4j_runFunction(ed.prop, ed.value);
} else if (ed.etype === "runFunctionWithResult") {
b4j_sendData(b4j_runFunction(ed.prop, ed.value));
} else if (ed.etype === "eval") {
b4j_eval(ed.value, ed.prop);
} else if (ed.etype === "evalWithResult") {
b4j_sendData(b4j_eval(ed.value, ed.prop));
} else if (ed.etype === "alert") {
window.alert(ed.prop);
}
};
}
I change on the click method to a onload method in the java webserver and it worked!
I want to use iCheck library:
https://github.com/fronteed/iCheck
http://fronteed.com/iCheck/
When i init the element with the library it get warped like the documentation describe https://github.com/fronteed/iCheck/#how-it-works but with opacity zero.
You can see it here: http://jsfiddle.net/buRq7/8/
$(".ex-f").iCheck();
somebody have the same issue?
Thanks
My code is:
/*!
* iCheck v1.0.1, http://git.io/arlzeA
* =================================
* Powerful jQuery and Zepto plugin for checkboxes and radio buttons customization
*
* (c) 2013 Damir Sultanov, http://fronteed.com
* MIT Licensed
*/
(function($) {
// Cached vars
var _iCheck = 'iCheck',
_iCheckHelper = _iCheck + '-helper',
_checkbox = 'checkbox',
_radio = 'radio',
_checked = 'checked',
_unchecked = 'un' + _checked,
_disabled = 'disabled',
_determinate = 'determinate',
_indeterminate = 'in' + _determinate,
_update = 'update',
_type = 'type',
_click = 'click',
_touch = 'touchbegin.i touchend.i',
_add = 'addClass',
_remove = 'removeClass',
_callback = 'trigger',
_label = 'label',
_cursor = 'cursor',
_mobile = /ipad|iphone|ipod|android|blackberry|windows phone|opera mini|silk/i.test(navigator.userAgent);
// Plugin init
$.fn[_iCheck] = function(options, fire) {
// Walker
var handle = 'input[type="' + _checkbox + '"], input[type="' + _radio + '"]',
stack = $(),
walker = function(object) {
object.each(function() {
var self = $(this);
if (self.is(handle)) {
stack = stack.add(self);
} else {
stack = stack.add(self.find(handle));
};
});
};
// Check if we should operate with some method
if (/^(check|uncheck|toggle|indeterminate|determinate|disable|enable|update|destroy)$/i.test(options)) {
// Normalize method's name
options = options.toLowerCase();
// Find checkboxes and radio buttons
walker(this);
return stack.each(function() {
var self = $(this);
if (options == 'destroy') {
tidy(self, 'ifDestroyed');
} else {
operate(self, true, options);
};
// Fire method's callback
if ($.isFunction(fire)) {
fire();
};
});
// Customization
} else if (typeof options == 'object' || !options) {
// Check if any options were passed
var settings = $.extend({
checkedClass: _checked,
disabledClass: _disabled,
indeterminateClass: _indeterminate,
labelHover: true,
aria: false
}, options),
selector = settings.handle,
hoverClass = settings.hoverClass || 'hover',
focusClass = settings.focusClass || 'focus',
activeClass = settings.activeClass || 'active',
labelHover = !!settings.labelHover,
labelHoverClass = settings.labelHoverClass || 'hover',
// Setup clickable area
area = ('' + settings.increaseArea).replace('%', '') | 0;
// Selector limit
if (selector == _checkbox || selector == _radio) {
handle = 'input[type="' + selector + '"]';
};
// Clickable area limit
if (area < -50) {
area = -50;
};
// Walk around the selector
walker(this);
return stack.each(function() {
var self = $(this);
// If already customized
tidy(self);
var node = this,
id = node.id,
// Layer styles
offset = -area + '%',
size = 100 + (area * 2) + '%',
layer = {
position: 'absolute',
top: offset,
left: offset,
display: 'block',
width: size,
height: size,
margin: 0,
padding: 0,
background: '#fff',
border: 0,
opacity: 0
},
// Choose how to hide input
hide = _mobile ? {
position: 'absolute',
visibility: 'hidden'
} : area ? layer : {
position: 'absolute',
opacity: 0
},
// Get proper class
className = node[_type] == _checkbox ? settings.checkboxClass || 'i' + _checkbox : settings.radioClass || 'i' + _radio,
// Find assigned labels
label = $(_label + '[for="' + id + '"]').add(self.closest(_label)),
// Check ARIA option
aria = !!settings.aria,
// Set ARIA placeholder
ariaID = _iCheck + '-' + Math.random().toString(36).replace('0.', ''),
// Parent & helper
parent = '<div class="' + className + '" ' + (aria ? 'role="' + node[_type] + '" ' : ''),
helper;
// Set ARIA "labelledby"
if (label.length && aria) {
label.each(function() {
parent += 'aria-labelledby="';
if (this.id) {
parent += this.id;
} else {
this.id = ariaID;
parent += ariaID;
}
parent += '"';
});
};
// Wrap input
parent = self.wrap(parent + '/>')[_callback]('ifCreated').parent().append(settings.insert);
// Layer addition
helper = $('<ins class="' + _iCheckHelper + '"/>').css(layer).appendTo(parent);
// Finalize customization
self.data(_iCheck, {o: settings, s: self.attr('style')}).css(hide);
!!settings.inheritClass && parent[_add](node.className || '');
!!settings.inheritID && id && parent.attr('id', _iCheck + '-' + id);
parent.css('position') == 'static' && parent.css('position', 'relative');
operate(self, true, _update);
// Label events
if (label.length) {
label.on(_click + '.i mouseover.i mouseout.i ' + _touch, function(event) {
var type = event[_type],
item = $(this);
// Do nothing if input is disabled
if (!node[_disabled]) {
// Click
if (type == _click) {
if ($(event.target).is('a')) {
return;
}
operate(self, false, true);
// Hover state
} else if (labelHover) {
// mouseout|touchend
if (/ut|nd/.test(type)) {
parent[_remove](hoverClass);
item[_remove](labelHoverClass);
} else {
parent[_add](hoverClass);
item[_add](labelHoverClass);
};
};
if (_mobile) {
event.stopPropagation();
} else {
return false;
};
};
});
};
// Input events
self.on(_click + '.i focus.i blur.i keyup.i keydown.i keypress.i', function(event) {
var type = event[_type],
key = event.keyCode;
// Click
if (type == _click) {
return false;
// Keydown
} else if (type == 'keydown' && key == 32) {
if (!(node[_type] == _radio && node[_checked])) {
if (node[_checked]) {
off(self, _checked);
} else {
on(self, _checked);
};
};
return false;
// Keyup
} else if (type == 'keyup' && node[_type] == _radio) {
!node[_checked] && on(self, _checked);
// Focus/blur
} else if (/us|ur/.test(type)) {
parent[type == 'blur' ? _remove : _add](focusClass);
};
});
// Helper events
helper.on(_click + ' mousedown mouseup mouseover mouseout ' + _touch, function(event) {
var type = event[_type],
// mousedown|mouseup
toggle = /wn|up/.test(type) ? activeClass : hoverClass;
// Do nothing if input is disabled
if (!node[_disabled]) {
// Click
if (type == _click) {
operate(self, false, true);
// Active and hover states
} else {
// State is on
if (/wn|er|in/.test(type)) {
// mousedown|mouseover|touchbegin
parent[_add](toggle);
// State is off
} else {
parent[_remove](toggle + ' ' + activeClass);
};
// Label hover
if (label.length && labelHover && toggle == hoverClass) {
// mouseout|touchend
label[/ut|nd/.test(type) ? _remove : _add](labelHoverClass);
};
};
if (_mobile) {
event.stopPropagation();
} else {
return false;
};
};
});
});
} else {
return this;
};
};
// Do something with inputs
function operate(input, direct, method) {
var node = input[0],
state = /er/.test(method) ? _indeterminate : /bl/.test(method) ? _disabled : _checked,
active = method == _update ? {
checked: node[_checked],
disabled: node[_disabled],
indeterminate: input.attr(_indeterminate) == 'true' || input.attr(_determinate) == 'false'
} : node[state];
// Check, disable or indeterminate
if (/^(ch|di|in)/.test(method) && !active) {
on(input, state);
// Uncheck, enable or determinate
} else if (/^(un|en|de)/.test(method) && active) {
off(input, state);
// Update
} else if (method == _update) {
// Handle states
for (var state in active) {
if (active[state]) {
on(input, state, true);
} else {
off(input, state, true);
};
};
} else if (!direct || method == 'toggle') {
// Helper or label was clicked
if (!direct) {
input[_callback]('ifClicked');
};
// Toggle checked state
if (active) {
if (node[_type] !== _radio) {
off(input, state);
};
} else {
on(input, state);
};
};
};
// Add checked, disabled or indeterminate state
function on(input, state, keep) {
var node = input[0],
parent = input.parent(),
checked = state == _checked,
indeterminate = state == _indeterminate,
disabled = state == _disabled,
callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled',
regular = option(input, callback + capitalize(node[_type])),
specific = option(input, state + capitalize(node[_type]));
// Prevent unnecessary actions
if (node[state] !== true) {
// Toggle assigned radio buttons
if (!keep && state == _checked && node[_type] == _radio && node.name) {
var form = input.closest('form'),
inputs = 'input[name="' + node.name + '"]';
inputs = form.length ? form.find(inputs) : $(inputs);
inputs.each(function() {
if (this !== node && $(this).data(_iCheck)) {
off($(this), state);
};
});
};
// Indeterminate state
if (indeterminate) {
// Add indeterminate state
node[state] = true;
// Remove checked state
if (node[_checked]) {
off(input, _checked, 'force');
};
// Checked or disabled state
} else {
// Add checked or disabled state
if (!keep) {
node[state] = true;
};
// Remove indeterminate state
if (checked && node[_indeterminate]) {
off(input, _indeterminate, false);
};
};
// Trigger callbacks
callbacks(input, checked, state, keep);
};
// Add proper cursor
if (node[_disabled] && !!option(input, _cursor, true)) {
parent.find('.' + _iCheckHelper).css(_cursor, 'default');
};
// Add state class
parent[_add](specific || option(input, state) || '');
// Set ARIA attribute
disabled ? parent.attr('aria-disabled', 'true') : parent.attr('aria-checked', indeterminate ? 'mixed' : 'true');
// Remove regular state class
parent[_remove](regular || option(input, callback) || '');
};
// Remove checked, disabled or indeterminate state
function off(input, state, keep) {
var node = input[0],
parent = input.parent(),
checked = state == _checked,
indeterminate = state == _indeterminate,
disabled = state == _disabled,
callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled',
regular = option(input, callback + capitalize(node[_type])),
specific = option(input, state + capitalize(node[_type]));
// Prevent unnecessary actions
if (node[state] !== false) {
// Toggle state
if (indeterminate || !keep || keep == 'force') {
node[state] = false;
};
// Trigger callbacks
callbacks(input, checked, callback, keep);
};
// Add proper cursor
if (!node[_disabled] && !!option(input, _cursor, true)) {
parent.find('.' + _iCheckHelper).css(_cursor, 'pointer');
};
// Remove state class
parent[_remove](specific || option(input, state) || '');
// Set ARIA attribute
disabled ? parent.attr('aria-disabled', 'false') : parent.attr('aria-checked', 'false');
// Add regular state class
parent[_add](regular || option(input, callback) || '');
};
// Remove all traces
function tidy(input, callback) {
if (input.data(_iCheck)) {
// Remove everything except input
input.parent().html(input.attr('style', input.data(_iCheck).s || ''));
// Callback
if (callback) {
input[_callback](callback);
};
// Unbind events
input.off('.i').unwrap();
$(_label + '[for="' + input[0].id + '"]').add(input.closest(_label)).off('.i');
};
};
// Get some option
function option(input, state, regular) {
if (input.data(_iCheck)) {
return input.data(_iCheck).o[state + (regular ? '' : 'Class')];
};
};
// Capitalize some string
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
};
// Executable handlers
function callbacks(input, checked, callback, keep) {
if (!keep) {
if (checked) {
input[_callback]('ifToggled');
};
input[_callback]('ifChanged')[_callback]('if' + capitalize(callback));
};
};
})(window.jQuery || window.Zepto);
$(".ex-f").iCheck();
And
<div class="my-checkbox">
<input class="ex-f" id="Finish" name="Finish" type="checkbox" value="1"> doesn't work
</div>
And
.my-checkbox {
border: 1px solid blue;
height: 20px;
}
.ex-f {
border: 1px solid red;
}
I found that the problem was with the CSS file, if it is not loaded the component is not showed, a working example:
http://jsfiddle.net/SUTMf/1/
$(document).ready(function(){
$('input').iCheck({
checkboxClass: 'icheckbox_flat-blue',
radioClass: 'iradio_square',
increaseArea: '20%' // optional
});
});
today i encountered this problem. and the same problem.
but finally solved.
and the reason is:
my local golobal variable name is "_type" which maybe the keyword in iCheck or somethin' else .
when i have iCheck in my Html, i found that _type is already used as the picture showed
wish could help u and the others.
If you place it before the iCheck code, it works for me:
$(".ex-f").iCheck();
//iCheck function
Demo
Well, same thing happened to me, and the problem was a conflict with other javascript code included in the page. I removed it or changed it and it worked. I hope this could help somebody, I don't put the code in here because could be anything, just check your code just in case same thing is happening to you.
Using a jQuery filter example I found. Here is my live example. Here is the CodePen, (also the Fiddle if you don't like CodePen).
After typing something in the input, the boxes do realign and the numbers dissapear. However, when you delete the text you inputted, the numbers do not reappear unless you refresh the page. I tried messing around with the code below but wasn't having any luck. Thanks for you help!
$('#sortable').change(
function(){
if ($(this).val().length) {
$('#number').hide();
}
else {
$('#number').show();
}
});
Try this out:- http://jsfiddle.net/adiioo7/nYYBU/10/
JS:-
(function ($) {
jQuery.expr[':'].Contains = function (a, i, m) {
return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
};
function listFilter(header, list) {
var form = $("<form>").attr({
"class": "filterform",
"action": "#"
}),
input = $("<input>").attr({
"class": "filterinput",
"type": "text",
});
$(form).append(input).appendTo(header);
$(input).change(function () {
var list = $("#sortable");
var filter = $(this).val();
console.log(filter.length);
if (filter.length > 0) {
$(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
$(".number").hide();
$(".numberstwo").hide();
} else {
console.log($(".number"));
$(".number").show();
$(".numberstwo").show();
$(list).find("a").parent().slideDown();
}
return false;
}).keyup(function () {
$(this).change();
});
}
$(function () {
listFilter($("#header"), $("#sortable"));
});
}(jQuery));
Here's updated js...
Checkout Demo Fiddle
(function ($) {
jQuery.expr[':'].Contains = function (a, i, m) {
return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
};
function listFilter(header, list) {
var form = $("<form>").attr({
"class": "filterform",
"action": "#"
}),
input = $("<input>").attr({
"class": "filterinput",
"type": "text",
});
$(form).append(input).appendTo(header);
$(input).change(function () {
var filter = $(this).val();
if (filter) {
$(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
$(list).find("a:Contains(" + filter + ")").parent().slideDown();
} else {
$(list).find("li").slideDown();
}
return false;
}).keyup(function () {
$(this).change();
if ($(this).val().length) {
$('.number').hide();
} else {
$('.number').show();
}
});
}
$(function () {
listFilter($("#header"), $("#sortable"));
});
}(jQuery));
To check the entered text I normally use keyup.
Change is not triggered when the user types something but when he types and exits the box.
$('#sortable').blur(function(){
var len = $(this).val().length;
if (len) {
$('#number').hide();
}
else {
$('#number').show();
}
I've got this function to check my form:
function checkFrm() {
$.each($('select'), function() {
var $this = $(this);
if( $this.val() === 'null') {
// do nothing
} else {
if($this.next('input').val().length < 1) {
return false;
}
}
});
}
When the user submits this, it runs this code, and ideally if the criteria is met the form won't submit because of the 'return false;' bit.
However, for some reason it's completley ignoring this!
If I set a return variable at the start like 'var toreturn = true;' then set 'toreturn = false' when the trigger is hit, then 'return toreturn;' right at the end it stops the form submitting just fine... however that's not much use, as the alerts and checks I run in between are all triggered at once which would be completely overwhelming for the user.
Any suggestions please?
Cheers :)
Returning false from the each will not return false from the function.
You will need to set a var to return false from the function also. You can still break out of the each by using return false as soon as your condition fails.
function checkFrm() {
var retVal=true;
$.each($('select'), function() {
var $this = $(this);
if( $this.val() === 'null') {
// do nothing
} else {
if($this.next('input').val().length < 1) {
//set the var to return from the function
retval = false;
//exit out of the each
return false;
}
}
});
return retVal;
}
When you call return false; it refurns false for the function
function() {
var $this = $(this);
if( $this.val() === 'null') {
// do nothing
} else {
if($this.next('input').val().length < 1) {
return false;
}
}
}
That is not work for you.
You better get an array of selects like this:
var selectsArray=document.getElementsByTagName("select");
and work with them in a loop.
for(var i=0; i< selectsArray.length;i++){
if( selectsArray[i].value === 'null') {
// do nothing
} else {
if(selectsArray[i].next('input').val().length < 1) {
return false;
}
}
}