How to avoid special characters on key press – javascript

Avoid keying of special characters.. hope this doesn’t need any explanation…


<input type="text" onkeypress="avoidSplChars(event)" />


 
function avoidSplChars(e) {
 e = e || window.event;
 var bad = /[^\sa-z\d]/i,
 key = String.fromCharCode( e.keyCode || e.which );

    if ( e.which !== 0 && e.charCode !== 0 && bad.test(key) ) {
          e.returnValue = false;
          if ( e.preventDefault ) {
              e.preventDefault(); 
          }
    } 
}
 

Happy Kooding… hope this helps!!


		
Advertisements

Example on Read & Write to Dictionary in JAVASCRIPT

Below sample code demonstrate on how to read/write dictionary in JS world.

Creating & Adding data to Dictionary

var workOrderDictionary = []; // declare dictionary

var companyId1 = 1;
var orders1 = [{ ProductId: 10, ProductName: Pen } , {ProductId: 20, ProductName: Eraser} ]
workOrderDictionary.push({ key: companyId1, value: orders1 });

var companyId2 = 2;
var orders2 = [{ ProductId: 101, ProductName: Lunch-Box } , {ProductId: 20, ProductName: Bottle } ]
workOrderDictionary.push({ key: companyId2, value: orders2 });

Reading the data from Dictionary

for (var key in workOrderDictionary) {
	if (workOrderDictionary.hasOwnProperty(key)) {
	    var orders =	workOrderDictionary[key];
	}
}

Happy Kooding… Hope this helps…!

Tips/Tricks: Javascript or JQuery

1) How to get difference between 2 days in days using Javascript


var noOfDays = (finishDate - startDate) / (1000 * 60 * 60 * 24);

2) Remove Last Comma from a string

var str = commaInLastStr.replace(/,\s*$/, "")

Happy Kooding… Hope this helps!

Tips/Tricks about KENDO

1) KENDO GRID: At anygiven time, if you want to access the edited or added data (before reload of grid/save)

var editableModel = $('#myGrid').data().kendoGrid.editable.options.model;

2) KENDO GRID: If you would like to update one of the property value manually for recent edited record in grid then


var editableModel = $('#myGrid').data().kendoGrid.editable.options.model;
editableModel.set("dobDate", '05/31/1983');

3) MONTH PICKER: Implementing month picker with Kendo. This would work with Grid Edit Pop also.

<input id="dobDate" type="date" class="input" name="dobDate" data-bind="value: dobDate" />
$(document).ready(function () {
 

$("#dobDate").kendoDatePicker({
start: "year",
depth: "year",
format: "MMMM yyyy",
parseFormats: ["MMMM yyyy"]
});


});

Month Picker cannot be achieved with Model binder as there is a known bug. The only available is the above

4) KENDO GRID: Format/Parse the date column (bound column)

columns.Bound(m =&amp;gt; m.DobDate).Width(50).Title("Dob Date").ClientTemplate("#= DobDate &amp;lt; 1/1/1900 ? '' : &nbsp; kendo.format('{0:MMMM yyyy}', DobDate) #")

5) KENDO DATE PICKER: Disable the control by editing it

<input id=”dobDate” type=”date” class=”input” name=”dobDate” onkeydown=”return false;”  data-bind=”value: dobDate” />

6) KENDO FILTER OPERATORS: Below are the few filter operators

  filter.push({ field: "IsNew", operator: "eq", value: 1 });

eqgtgteltteneq

7) READONLY:

 @(Html.Kendo().DatePicker().Value(DateTime.Now)
 .Name("myDate").Min(DateTime.Now)
 .HtmlAttributes(new { style = "width: 100%", @readonly="readonly" }))

or


$("#myDate").kendoDatePicker(); 

var myDate= $("#myDate").data("kendoDatePicker"); 

myDate.readonly(true);

8) NUMERIC TEXTBOX: Don’t allow decimal value and don’t allow negative value (define min value)

a) format allows you to ignore/avoid entering decimal value

b) min allows you to set the min value to zero


$("#Hours").kendoNumericTextBox({ decimals: 0, format: "#", min: 0 });

9) HIDE/SHOW KENDO DROPDOWNLIST: Below is the syntax to hide/show kendo dropdownlist
HIDE:

 $("#ddlCountries").closest(".k-widget").hide();

SHOW:

 $("#ddlCountries").closest(".k-widget").show();

10) Kendo Grid Filter Configuration : For a Kendo Grid, if you would like to customize the filter menu below is how you can do


@(Html.Kendo().Grid<UserModel>()
    .Name("MyGrid")
    .ColumnMenu()
    .Filterable(f => f.Operators(o => o.ForString(s => s
        .Clear()
        .Contains("Contains")
        .DoesNotContain("Does not contain")
        .EndsWith("Ends with")
    )))
// other configuration goes
)

If you would like to customize to a specific column then you would do same above filter configuration to a column rather than entire grid


@(Html.Kendo().Grid<UserModel>()
    .Name("MyGrid")
    .Columns(columns =>
          {
              columns.Bound(m => m.UserName)
              .Filterable(f => f.Operators(o =>
              o.ForString(s => s.Clear().Contains("Contains")
              .DoesNotContain("Does not contain")
              .EndsWith("Ends with")
    )))

})
)

11) Kendo Grid Clear Selected Row :


            var grid = $("#myGrid").data("kendoGrid");
            grid.clearSelection();

Happy Koooding…..  Hope this helps!….

Calling Web Service from Javascript

Hi,

Now we will discuss how to call web service from javascript.

This example demonstrates of

1. Calling web service method from javascript after page loads completely (async) &

2. This method returns XML string &

3. Displays XML node content div &

4. Between if there is any delay from web service, we need to show loading image or loading text.

Lets get into details

  • Add new Item, select webservice from template & name it as “ServiceOne.asmx”
    • Add  [System.Web.Script.Services.ScriptService] attribute to ServiceOnce class
    • Add below method to ServiceOne class
    • [WebMethod]publicstring GetResponse(string callerName){string txt = string.Empty;txt = “<bookstore><book>”;txt = txt + “<title>Everyday Italian</title>”;txt = txt + “<author>Giada De Laurentiis</author>”;txt = txt + “<year>2005</year>”;txt = txt + “</book></bookstore>”;if (callerName == string.Empty)thrownewException(“Web Service Exception: invalid argument”);Thread.Sleep(5000); // To get response delay, forced to sleepreturnstring.Format(txt.ToString());}  
  • Add Script Manager and add Service reference to default.aspx as shown below

<asp:ScriptManagerID=”ScriptManager1″runat=”server”> <Services><asp:ServiceReferencePath=’~/ServiceOne.asmx’/></Services></asp:ScriptManager>

  • Now lets add DIV, which will show loading text if there is any delay response from Web Service & when there is response from web service it will  display XML NODE content

 <divid=”lblResponse”></div>

  • Now Lets the javascript function code which will call web method & the response from web method can be Success/Completed response, TimeOut response & Error response. Below sendRequest function is called in BodyLoad event, & first statement shows loading text in div until we get response from Web Service

This function pass static string value to web method & response will be either completed, timeout or error. So we define respective function names in web method calls.

ServiceOne is web service

GetResponse is web method defined in ServiceOne service class

function SendRequest() {document.getElementById(“lblResponse”).innerHTML = “Please wait loading……. “;ServiceOne.GetResponse(

“TESTING TO BE ……..”, OnComplete, OnError, OnTimeOut);}

  • On Success/Complete reponse we need to parse XML string & read the Title XML node from XML string & display in lblResponse DIV as shown below

function OnComplete(arg) {//alert(arg);

if (window.DOMParser) {parser = new DOMParser();xmlDoc = parser.parseFromString(arg,

“text/xml”);}

else// Internet Explorer

{

xmlDoc = new ActiveXObject(“Microsoft.XMLDOM”);xmlDoc.async = “false”;xmlDoc.loadXML(arg);

}

x = xmlDoc.getElementsByTagName(“title”)[0];y = x.childNodes[0];

txt = y.nodeValue;

document.getElementById(“lblResponse”).innerHTML = txt;}

  • Whenever there is ErrorReponse then below function will be called

function OnTimeOut(arg) {alert(“timeOut has occured”);}

  • Whenever there is TimeOut response below function will be called

function OnError(arg) {alert(“error has occured: “ + arg._message);}

  • Finally call sendRequest JS function in body load event as shown below

<bodyonload=”return SendRequest();”>

  • Now lets execute this & checkout the output