Creating Custom jQuery Widget
Hi I just came across a greate website http://bililite.com/blog/understanding-jquery-ui-widgets-a-tutorial/
There I learned how to create custom jQuery widget. I have tried to create my one TexBox widget.
This widget will help to takecare each validations we want to do on a TextBox. Currently I have listed only 2 validations. Similarly we can put many validations.
I want to share that.
myWidget.js
$(function(){
$.widget("ui.TextBox", {
options: {
color:"red"
,required:true
,numeric:true
,msg : {req: "Please enter some text" , num: "Text should be alphanumeric" }
}
,_init : function (){
this._setColor();
}
,_setColor:function ( ) {
this.element.css({"background-color":this.options.color});
}
,off:function ( ) {
this.element.css({"background-color":""});
this.destroy( );
}
,_rules : {num:/[0-9]/}
,validate : function ( ) {
var o = this.options,ret=true;
this.element.removeClass("ui-state-error");
if (o.required) {
var txt=$.trim( this.element.val( ) );
if(txt==="") {
ret = false;
this.element.addClass("ui-state-error");
alert(o.msg.req) ;
}
}
if(ret && ! this._rules.num.exec(txt)) {
ret = false;
this.element.addClass("ui-state-error");
alert(o.msg.num) ;
}
};
});$("#txtfact").myWidget({color:"khaki",msg:{req:"Please enter your name !!!"}});
$("#btnon").click( function( ) {
$("#txtfact").TextBox("validate");
});
$("#btnoff").click( function( ) {
$("#txtfact").TextBox("off");
});
});
<!--pan class="hiddenSpellError" pre=-->DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=Content-Type content="text/html; charset=unicode">
<META content="MSHTML 6.00.2900.3603" name=GENERATOR>
<link href="C:\rupesh\css\redmond\jquery-ui-1.8.6.custom.css" rel="stylesheet" type="text/css" />
<script type="text/<span class="><!--mce:0--></script>
<script type="text/<span class="><!--mce:1--></script>
<script type="text/javascript" src="C:\rupesh\js\myWidget.js"></script>
</HEAD>
<BODY>
Enter Account Number <input type="text" value="" id="txtfact" />
<button id="btnon">Validate</button>
<button id="btnoff">Remove Widget</button>
</BODY>
</HTML>
Comments