a developer's notes – a semi-technical web development BLOG

May 13, 2015

Javascript Namespace Function Expression Sample

Filed under: Javascript / JQuery — Duy Nguyen @ 12:05 pm
Tags: , ,

A sample of how to structure your JS file per page. This works good for organizational purposes and it will avoid name clashing.

var PageName = {

// define your functions as variables.
    bindCheckBox: function () {
        $("#mycheckbox").on("click", function () {
            PageName.checkboxClick();
        });
    },

    enableConfirmButton: function (bool) {
        if (bool)
            $("#mybutton").removeAttr("disabled");
        else
            $("#mybutton").attr("disabled", "disabled");
    },

    checkboxClick: function () {
        if ($("#mycheckbox").is(":checked"))
            this.enableConfirmButton(true);
        else
            this.enableConfirmButton(false);
    }
}

// Start of document.ready in jquery
$(function () {
    // calling the global variable you created.
    PageName.bindCheckBox();
});

If you want to use an Immediately Invoked Function Expression (IIFE)


(function() {
     // This creates a function that invokes itself with NO GLOBAL FUNCTIONS.
}());

November 13, 2014

Form Validation with Javascript events. Handle Input, Paste, and Keyup across all browsers

Filed under: Javascript / JQuery — Duy Nguyen @ 12:47 pm
Tags: , , , , , , , ,

While testing mobilePay in Chrome on an Android device, it was discovered that the
keyupevent was not firing for validation. Our response was to include input, an HTML5 event, to ensure that changes were firing the validation handlers.

$('form :input').on('keyup input', this.toggleSubmitBtn);

Currently, we are validating the form on every user’s input change, which would enable/ disable the submit button. The disadvantage of this is that we have to capture every single event that the user could possibly interact with the element.

The paste event is one of the events that we recently have implemented to handle. The inputevent we realize fires when the user pastes in an HTML5 browser, which means only non-HTML5 browsers actually need the pasteevent. Below is a table of support for paste validation:

$('form :input').on('keyup input paste', this.toggleSubmitBtn);

The paste event fires across all test devices, but javascript validation logic is carried out beforethe data on the clipboard gets placed into the element. Because all the browsers except for IE8 supported HTML5, however, the inputevent fired afterthe clipboard data was placed in the element. Without the inputevent, none of the browsers supported paste validation.

Solution

InputPropertyChange: function () {
    if (!window.addEventListener) { //IE 5-8 
        var $inputs = $("input[type!='hidden']");
        $.each($inputs, function (index, input) {
            $(index).on('paste'), function () {
                setTimeout( function() {
                    $(input).trigger('keyup');
                }, 250);
            }                
        });
    }
}

This was written up by my colleague Will Hanson and I.

August 29, 2013

Jquery Error: SCRIPT1028: Expected identifier, string or number

Filed under: Javascript / JQuery — Duy Nguyen @ 5:04 pm
Tags: , , , ,

When getting this error in Internet Explorer, check the mode that IE is running. Make sure you are not running in Quirks Mode, or Compatibility Mode, or IE 7/8 Standards.

Also, check under Tools >> Compatibility View Settings >> and uncheck

“Display all websites in Compatibility View”
“Display all intranet sites in Compatibility View”

May 7, 2013

Javascript function to convert number to currency.

Filed under: Javascript / JQuery — Duy Nguyen @ 4:25 pm
Tags: , , ,

Read Here


function format1(n, currency) {
    return currency + " " + n.toFixed(2).replace(/./g, function(c, i, a) {
        return i > 0 && c !== "." && (a.length - i) % 3 === 0 ? "," + c : c;
    });
}

function format2(n, currency) {
    return currency + " " + n.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
}

var numbers = [1, 12, 123, 1234, 12345, 123456, 1234567, 12345.67];

document.write("<p>Format #1:</p>");
for (var i = 0; i < numbers.length; i++) {
    document.write(format1(numbers[i], "£") + "<br />");
}

document.write("<p>Format #2:</p>");
for (var i = 0; i < numbers.length; i++) {
    document.write(format2(numbers[i], "$") + "<br />");
}

Here is the output

Format #1:
£ 1.00
£ 12.00
£ 123.00
£ 1,234.00
£ 12,345.00
£ 123,456.00
£ 1,234,567.00
£ 12,345.67

Format #2:
$ 1.00
$ 12.00
$ 123.00
$ 1,234.00
$ 12,345.00
$ 123,456.00
$ 1,234,567.00
$ 12,345.67

April 11, 2013

Parsing a Query String into an array with JavaScript

Filed under: Javascript / JQuery — Duy Nguyen @ 9:50 pm
Tags: , , , , , , , , ,

This brilliant method belongs to Joe Zim’s JavaScript Blog.

Here is the function.

    var parseQueryString = function( queryString ) {
        var params = {}, queries, temp, i, l;
     
        // Split into key/value pairs
        queries = queryString.split("&");
     
        // Convert the array of strings into an object
        for ( i = 0, l = queries.length; i < l; i++ ) {
            temp = queries[i].split('=');
            params[temp[0]] = temp[1];
        }
     
        return params;
    };

Using the function.

   function Test() {
        var qstring = "apple=7sf&orange=242&bananna=47614&cherry=8139";
        var myNewArray = parseQueryString(qstring);
    }

As you can see, you now have an array of all of your query strings!

parseQstring

March 27, 2013

$document.ready() Shortcut in jQuery

Filed under: Javascript / JQuery,Uncategorized — Duy Nguyen @ 11:52 am
Tags: , , , ,

You can just use this:

$(function() {
     // do something on document ready
});

It is the same as this:

$(document).ready(function(){
     // do something on document ready
});

But if you’ve placed all your scripts right before the body closing tag, this is the same as $(document).ready.

How to debug into javascript/jquery when working with Visual Studio

Filed under: ASP.NET,Javascript / JQuery — Duy Nguyen @ 12:12 am
Tags: , , ,

Add debugger in your javascript code.

Within your Javascript code, add the line

debugger;

1. Using Visual Studio:
You can execute (F5) your application and debug with Visual Studio and the application will stop on your line of code. Note** You have to use Internet Explorer if you want to use Visual Studio.

js_vs

2. Use Chrome:
Just add the same line of code but have the Developer Tools open when you navigate to your page that executes your javascript code.

js_chrome

3. Use Firefox:
Just add the same line of code but have Firebug open when you navigate to your page that executes your javascript code.

js_firefox

October 4, 2011

Can’t debug into a Javascript file. Error “No Disassembly Available” or “This breakpoint will not currently be hit. No symbols have been loaded for this document”

Ever put a break point in visual Studio 2010 on a .js file to get this?

This breakpoint will not currently be hit. No symbols have been loaded for this document.”

Then you decide to user the ‘debugger;’ statement. But then Visual Studio gives this error: “no disassembly available“.

You are probably loading your .js file dynamically. If you are, remove (or comment out) where you are loading and load it with an explicit script tag.

example: I was loading the script file like this:

<script src="<%=Url.StaticContent("/MyApplication/Scripts/views/script.js")%>" type="text/javascript" ></script>

I just commented out that line and hard coded the script file like this:

<script src="http://localhost/MyApplication/Scripts/views/script.js" type="text/javascript"></script>

Now I am able to user the debugger; statement AND able to put a break point in Visual Studio.

September 5, 2011

To prevent IE from locking up on long running scripts

Filed under: Javascript / JQuery — Duy Nguyen @ 2:13 pm
Tags: , , , , , , , , ,

To prevent IE from locking up on long running scripts, break out your logic with the Javascript setTimeout method.

I was doing this but it was not working. This was not working because of the way I implemented the looping.


    var size = 100000000; //10,000,000 is ok, 100,000,000 is bad    
    var mystring = "";
    var chunkSize = size / 10000;
    var chunkSizeCounter = 0;

function button2_clientClick() {
          
        for (var i = 0; i < size; i++) {
            AddToMyString();
        }

        return false;
    }


    function AddToMyString() {
        if (chunkSizeCounter == chunkSize) {
            chunkSizeCounter = 0;
            setTimeout("AddToMyString()", 100);
        }

        mystring = mystring + ",";
        chunkSizeCounter++;   
    }

But I need to do this. This allowed the browser to continue to loop and process without it locking up. This is because the setTimeOut function runs on a parallel process, which allowed the browser to not “wait” for the processing to complete. Unlike the previous loop, it was taking too long for the For loop to complete. The second implementation allowed the concatString() function to complete on each interval.

    var size = 100000000; //10,000,000 is ok, 100,000,000 is bad    
    var mystring = "";
    var chunkSize = size / 10000;
    var chunkSizeCounter = 0;

    function button2_clientClick() {
        
        concatString();
        return false;
    }

    function concatString() {
        mystring += ",";
        chunkSizeCounter++;
        if (chunkSizeCounter < size)
            window.setTimeout(concatString, 10);
    }

Get a Javascript DOM object from a jQuery object

Filed under: Javascript / JQuery — Duy Nguyen @ 1:49 pm
Tags: , , , , ,

jQuery object is a wrapper around the js DOM object. If you want to get the DOM object from the jQuery object, you should use get() method.

For example, if the jQuery object includes only one DOM object, you can use

$("div").get(0)

or

$("div")[0]

However, if you have multiple DOM objects, you can use

$("div").get()

var myvar;
myvar= $(‘#<%=selectedProductionIdsHdnVl.ClientID%>‘).get(0);
myvar.value = “b”;

same as

document.getElementById(“<%=selectedProductionIdsHdnVl.ClientID%>“).value = “B”;

This allowed me to use the ASP Hidden field and have the OnValueChanged server side event get fired.

Next Page »

Create a free website or blog at WordPress.com.