javascript e.preventDefault() and return false

Hello,

In javascript; When I want to prevent other event handlers from executing after a certain event is fired, I can use one of two techniques; e.preventDefault() or return false.

So what is the difference in between e.preventDefault() and return false and When to use return false and when preventDefault()?

First we need to understand below things
1. e.preventDefault() = It stops the browsers default behaviour
2. e.stopPropagation() = It prevents the event from propagating.

Return False :
when we call return false in our function then it does below things
1. e.preventDefault()
2. e.stopPropagation()
3. Stops the callback execution and returns immediately

e.preventDefault() :
when we call e.preventDefault() in our function then it does only one thing i.e e.preventDefault()

In short return false takes things a bit further in, it also prevents that event from propagating (or “bubbling up”) the DOM.
function()
{
return false;
}

is euqal to

function(e)
{
e.preventDefault();
e.stopPropagation();
}

Hope this will help you in understanding e.preventdefault() and return false;

example of jqGrid

Hello all,

Recently i have implemented jqGrid in my one of project. I have prepare one simple example for jqGrid which i want to share with you all.

First download jqGrid from jquery or github. Extract it to your project. I have created Default.aspx to enter my grid. Add jqGrid reference files. After that add script tag and enter following code.

         jQuery("#colr").jqGrid({
                sortable: true,
                url: 'GetData.aspx',
                datatype: 'json',
                jsonReader: {
                    root: "rows",
                    page: "page",
                    total: "total",
                    records: "records",
                    repeatitems: true,
                    cell: "cell",
                    id: "id",
                },
                colNames: ['', 'ID', 'Title', 'Alternate', 'Starring', 'Added On', 'Barcode', 'Director', 'Writer', 'Dstributor', 'Studio', 'Runtime'],
                colModel: [
                            { name: 'select', width: 25, sortable: false, align: "center" },
                            { name: 'movieID', index: 'movieID', width: 55 },
                            { name: 'movieTitle', index: 'movieTitle', width: 90 },
                            { name: 'alternateTitle', index: 'alternateTitle', width: 100 },
                            { name: 'starring', index: 'starring', width: 80 },
                            { name: 'createdDate', index: 'createdDate', width: 80, align: "center" },
                            { name: 'barcode', index: 'barcode', width: 80 },
                            { name: 'director', index: 'director', width: 150, sortable: false },
                            { name: 'writer', index: 'writer', width: 100 },
                            { name: 'distributor', index: 'distributor', width: 100 },
                            { name: 'studio', index: 'studio', width: 100 },
                            { name: 'runtimtInMinute', index: 'runtimtInMinute', width: 100 }
                            ],
                rowNum: 20,
                rowList: [10, 20, 30, 50],
                pager: '#pcolr',
                sortname: 'movieID',
                viewrecords: true,
                sortorder: "desc",
                shrinkToFit: false,
                width: 900,
                height: 500,
                caption: "jqGrid Example"
            });

            jQuery("#colr").jqGrid('navGrid', '#pcolr', { add: false, edit: false, del: false, search: false });
            // Column Button
            jQuery("#colr").jqGrid('navButtonAdd', '#pcolr', {
                caption: "",
                buttonicon: "ui-icon-calculator",
                title: "Reorder Columns",
                onClickButton: function ()
                {
                    jQuery("#colr").jqGrid('columnChooser');
                }
            });

            // Add Button
            jQuery("#colr").navSeparatorAdd('#pcolr', {
                sepclass: "ui-separator",
                sepcontent: ''
            })
            .navButtonAdd('#pcolr', {
                caption: "",
                buttonicon: "ui-icon-plus",
                title: "Add",
                onClickButton: function ()
                {
                    alert('Add');
                },
                position: "last"
            })
            .navButtonAdd('#pcolr', {
                caption: "",
                buttonicon: "ui-icon-pencil",
                title: "Edit",
                onClickButton: function ()
                {
                    alert('Edit Row : ' + jQuery('#colr').jqGrid('getGridParam', 'selrow'));
                },
                position: "last"
            })
            .navButtonAdd('#pcolr', {
                caption: "",
                buttonicon: "ui-icon-cancel",
                title: "Delete",
                onClickButton: function ()
                {
                    alert('Delete Row : ' + jQuery('#colr').jqGrid('getGridParam', 'selrow'));
                },
                position: "last"
            });
        });

In html add following code. This is for jqGrid grid and pager.

    

Now create one GetData.aspx and write following code in pageLoad.

int page = int.Parse(Request.QueryString["page"] == null ? "1" : Request.QueryString["page"].ToString());
            int rp = int.Parse(Request.QueryString["rows"] == null ? "200" : Request.QueryString["rows"].ToString());
            string sortname = Request.QueryString["sidx"] == null ? "movieID" : Request.QueryString["sidx"].ToString();
            string sortorder = Request.QueryString["sord"] == null ? "desc" : Request.QueryString["sord"].ToString();

            string sort = String.Format("ORDER BY {0} {1}", sortname, sortorder);

            int rowPage = rp;

            if (page == 0)
                page = 1;

            if (rp == 0)
                rp = 200;

            int start = ((page - 1) * rp);

            if (start != 0)
            {
                rp = start + rp;
                start = start + 1;
            }

            string limit;// = String.Format( "LIMIT {0}, {1}", start, rp );
            //limit = "";
            limit = String.Format("WHERE row >= {0} and row <= {1}", start, rp);

            Response.ClearHeaders();
            Response.AppendHeader("Expires", "Mon, 26 Jul 2012 05:00:00 GMT");
            Response.AppendHeader("Last-Modified", DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString());
            Response.AppendHeader("Cache-Control", "no-cache, must-revalidate");
            Response.AppendHeader("Pragma", "no-cache");
            //Response.AppendHeader("Content-type", "text/xml");
            Response.AppendHeader("Content-type", "text/json");

            List data = GetMovieDataTable(sort, limit);

            // Generating JSON Data

            StringBuilder jsonData = new StringBuilder();
            jsonData.AppendLine("{");
            jsonData.AppendLine(String.Format("\"total\": {0},", Math.Ceiling(Convert.ToDecimal(this.GetTotalRecords()) / rowPage)));
            jsonData.AppendLine("\"page\": \"" + page.ToString() + "\",");
            jsonData.AppendLine(String.Format("\"records\": {0},", this.GetTotalRecords()));
            jsonData.AppendLine("\"rows\": [");

            bool rc = false;

            foreach (Movie mObj in data)
            {
                if (rc)
                {
                    jsonData.AppendLine(",");
                }

                jsonData.Append(
                    String.Format("{{\"id\":\"{1}\",\"cell\":[\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\", \"{6}\", \"{7}\",\"{8}\", \"{9}\", \"{10}\", \"{11}\"]}}",
                        "",
                        mObj.movieID,
                        mObj.movieTitle == null ? "" : ("" + StringValidate(mObj.movieTitle) +
                        " "),
                        mObj.alternateTitle == null ? "" : StringValidate(mObj.alternateTitle),
                        mObj.starring == null ? "" : StringValidate(mObj.starring),
                        mObj.createdDate,
                        mObj.barcode,
                        mObj.director == null ? "" : StringValidate(mObj.director),
                        mObj.writer == null ? "" : StringValidate(mObj.writer),
                        mObj.distributor == null ? "" : StringValidate(mObj.distributor),
                        mObj.studio == null ? "" : StringValidate(mObj.studio),
                        mObj.runtimtInMinute
                        ));

                rc = true;
            }

            jsonData.AppendLine("]");
            jsonData.Append("}");

            Response.Write(jsonData.ToString());
            Response.End();

That’s it. You are ready with your code. I am attaching sample project in zip format to give more idea.
jqGridExample

show error in jqGrid

Hello all,

Show error in jqGrid use loadError attribute. When the grid is loading and any error occurs it will seen in loadError attribute.

To set loadError use following code.

....
        loadError: function (jqXHR, textStatus, errorThrown)
        {
            alert('HTTP status code: ' + jqXHR.status + '\n' +
              'textStatus: ' + textStatus + '\n' +
              'errorThrown: ' + errorThrown);
            alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
        }
....

It will help to show response error.

Reset control value in js

Today, i want to share one js function with all of you. Which is useful to reset controls value.

function resetControl(element)
{
    try
    {
        switch (Utilities.GetTagName(element).toLowerCase())
        {
            case "":
                {
                    break;
                }
            case "input":
                {
                    switch ((element.type + "").toLowerCase())
                    {
                        case "":
                            {
                                element.value = "";
                                break;
                            }
                        case "text":
                            {
                                element.value = "";
                                break;
                            }
                        case "password":
                            {
                                element.value = "";
                            }
                    }
                    break;
                }
            case "select":
                {
                    Utilities.deselectAllOptions(element);
                    if (element.options.length > 0)
                    {
                        element.options[0].selected = (!element.multiple);
                    }
                    break;
                }
            case "textarea":
                {
                    element.value = "";
                    break;
                }
        }
    }
    catch (ex)
    {
        return;
    }
    return;
};

above function is useful to reset html controls.

Call cross-domain service from js

Hello All,

Today, i want to share how to call cross-domain service from js.

We may call service from js with ajax call. Following function will return json data from service. Make sure your service also return json data too.

$.getData = function(url, options) {
            $.ajax({
                url: url,
                type: "POST",
                data: JSON.stringify(options),
                dataType: "json",
                async: false,
                success: function(msg) {
                    returnData(options.method, jQuery.parseJSON(msg.result));
                }
            });
        };

Now, to call service write as follow

function getDataFromService() {
        $.getData("service_url/WebServices.ashx", { method: 'method_name', params: { /* if any */ }
        });
    };

To use parameter in your service write as “param_name1″ : param_value, “param_name2″ : param_value…

That’s it. enjoy your service call. Your browser will block cross-domain service so, make sure you will remove that option from browser settings.

Image upload in tiny-mce editor

Hello,

Tiny-mce editor not providing image upload features. You have to use other plugins for image upload.
Sometimes plugin not work correctly. So, i have build my own page to upload image.

To upload image in tiny-mce editor first write your page name in tiny-mce editor initialization.

....

tinyMCE.activeEditor.windowManager.open({

file: '../../../FileUploadPopUp.aspx',
............

});

....

file: option is set your page which you want to call.
Find attachment for FileUploadPopUp page.
FileUploadPopUp

Use tiny-mce editor for specific textboxes

Hello all,

Today, i want show you use of tiny-mce editor.

Download tiny-mce editor. Copy directory to your website and add following code to your page.

    
    

Now, on your page js write below code. It will apply tiny-mce only on those text box which you want.

function page_load()
{
tinyMCE.execCommand('mceAddControl', false, 'textbox_name');
.....
.....
}

To retrieve or assign value of text box use below code.

// To assign
this.textbox_name.value = "your value";

// To retrieve
var temp = tinyMCE.get('textbox_name').getContent();

Check all checkbox of Repeater

Hello All,

Today I am representing javascript functionality to check/uncheck all checkboxes of Repeater.

If we use asp.net for check/uncheck then it will postback and degrade the performance.

See below example to check/uncheck all checkboxes of Repeater without postback

see below general javascript “checkall” function which is used for all binding controls in asp.net like repeater, gridview, datalist etc.

function CheckAll(checkAllBox, fieldName)
{
    ///Checks all the Checkboxes
    ///Checkbox in the header
    ///checkBox name to match
    var frm = document.forms[0];

    var inputs = document.getElementsByTagName("input");

    var actVar = checkAllBox.checked;

    for (i = 0; i < inputs.length; i++)
    {
        e = inputs[i];

        if (e.type == 'checkbox' && e.name.indexOf(fieldName) != -1)
        {
            e.checked = actVar && (!e.disabled);
        }
    }
}

How can we call above function in asp.net Repeater control
see below example



   
Name
Email
<%# Eval("Name")%>
<%# Eval("Email")%>

How to check maxlength of textarea

Hello All,

We know that TextBox has maxlength attribute to limit the number of allowed characters but Textarea doesn’t have any attribute to limit the number of allowed characters. We can control it by using simple javascript.

see below javascript function to control the characters in textarea and asp.net multiline textbox control

function checkTextAreaMaxLength(textBox, e, length)
{   
    var mLen = textBox["MaxLength"];
    if(null==mLen)
        mLen=length;
    
    var maxLength = parseInt(mLen);
    if(!checkSpecialKeys(e))
    {   
         if(textBox.value.length > maxLength-1)
         {
            if(window.event)//IE
              e.returnValue = false;
            else//Firefox
                e.preventDefault();
         }
    }   
}

see below example to limit the characters in a textarea for not exceeding more than 500 characters.


same way, we can control the characters in a asp.net multiline textbox.


Javascript code for “Add To Favorites” in browser

Whenever i open any site today, i can see “Add to Favorite” link on it. So, i think why should i not try this??

When i was search code for it, i don’t get exact…Simple code for “Add To Favorite” is window.external.AddFavorite(url, title).

But it was not working in all browser….So today i come up with multibrowser “Add To Favorite” link.

<script type="text/javascript">

function CreateBookmarkLink()
{
title = "Your Display Title";
url = "URL To Save in BookMark";
if (window.sidebar)
{
// Mozilla Firefox Bookmark
window.sidebar.addPanel(title, url, "");
}
else if (window.external)
{
// IE Favorite
window.external.AddFavorite(url, title);
}
else if (window.opera && window.print)
{
// Opera Hotlist
return true;
}
}
if (window.external)
{
document.write('<a href ="javascript:CreateBookmarkLink()");">Add to Favorites</a>');
}
else if (window.sidebar)
{
document.write('<a href ="javascript:CreateBookmarkLink()");">Bookmark Page</a>');
}
else if (window.opera && window.print)
{
document.write('<a href ="javascript:CreateBookmarkLink()");">Add Bookmark</a>');
}
</script>