Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, September 10, 2015

AngularJS - Multiple Select Dropdown with Comma Seperated ngModel

My requirement is to create multiple select dropdown and ngmodel should result with comma seperated value. For that, i have created following directive

      app.directive('multiSelectDropDown', function () {
        return {
            restrict: 'E',
            scope: {
                model: '=',
                options: '='
            },
            template: "<div class='btn-group dropdown' style='width:100%'>" +
             "<input type='text' ng-model='model' style='width:92%;height:36px;float:left;' class='dropdown-toggle' data-toggle='dropdown' placeholder='Click to select' disabled>" +
             "<button class='btn btn-small dropdown-toggle' style='width:8%;height:36px;' data-toggle='dropdown'  ><span class='caret'></span></button>" +
                     "<ul class='dropdown-menu'  style='width:100%'  aria-labelledby='dropdownMenu'>" +
                         "<li><a data-ng-click='selectAll()'><i class='glyphicons ok'></i>  Select All</a></li>" +
                         "<li><a data-ng-click='deselectAll();'><i class='glyphicons remove'></i>  Deselect All</a></li>" +
                         "<li class='divider'></li>" +
                         "<li data-ng-repeat='option in options'>" +
                         "<a data-ng-click='setSelectedItem()'><span data-ng-class='isChecked(option)'></span>&nbsp;{{option}}</a>" +
                         "</li>" +
                     "</ul>" +
                 "</div>",
            controller: function ($scope) {

                $scope.selectAll = function () {
                    $scope.model = _.unique($scope.options).toString();
                };
                $scope.deselectAll = function () {
                    $scope.model = "";
                };

                $scope.setSelectedItem = function () {
                    var selected = this.option;
                    if ($scope.model != undefined && $scope.model != null && _.contains($scope.model.split(','), selected)) {
                        $scope.model = _.without($scope.model.split(','), selected).toString();
                    } else {
                        var arrayModel = [];
                        if ($scope.model != undefined && $scope.model != null && $scope.model != "")
                             arrayModel = $scope.model.split(',');
                        arrayModel.push(selected);
                        $scope.model = arrayModel.toString();;
                    }
                    return false;
                };
                $scope.isChecked = function (selected) {
                    if ($scope.model != undefined && $scope.model != null && $scope.model != "") {
                        if (_.contains($scope.model.split(','), selected)) {
                            return 'glyphicons ok';
                        }
                    }
                    return false;
                };
            }
        }
    });


In module, we can include this directive and just we set in html as follows

//ArrayList = [‘A1’,’A2’,’A3’]
//modelToBind = “A1,A2”


<multi-select-drop-down model="modelToBind" options="ArrayList"></multi-select-drop-down>

Monday, July 20, 2015

JavaScript - Pinch and Zoom using Hammer JS

How to zoom content and not header or footer. Follow as below

Its simple with Hammer JS, download from here http://hammerjs.github.io/  or from Nuget package.

HTML Page:

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
...
<script src="~/Scripts/hammer.min.js"></script>
...
<div id="someContainer">
..Some Content goes here
</div>

<script type="text/javascript">
    $(document).ready(function () {
        //Regisister here
        var element = $('#someContainer');
        contentPinchIntializer(element[0]);
    });

</script>


JavaScript to Pinch and Zoom content:
- Here i created max scale as 5, you can customize it
- Here i added Margin left and Margin Right to avoid space issue while on zooming, you can adjust the pixels however you want
- Added touch-action to enable horizontal scrolling

var contentPinchIntializer = function (element) {
    var scale = 1;
    var currentScale = null;
    var currentMarginLeft = null;
    var currentMarginRight = null;

    var pinchInHanlder = function (e) {
        scale = event.gesture.scale == null ? scale : event.gesture.scale;
        currentScale = currentScale == null ? scale : currentScale;
        currentMarginLeft = currentMarginLeft == null ? $(this).css("margin-left") : currentMarginLeft;
        currentMarginRight = currentMarginRight == null ? $(this).css("margin-right") : currentMarginRight;

        if (scale < currentScale) {
            scale = currentScale + 0.1;
            $(this).css({ "margin-left": currentMarginLeft, "margin-right": currentMarginRight });
        }

        scale = ('scale(' + (scale - 0.1).toString() + ')');

        $(this).css({ 'transform': scale, '-ms-transform': scale, '-webkit-transform': scale });
    };

    var pinchOutHandler = function (e) {
        scale = event.gesture.scale == null ? scale : event.gesture.scale;
        currentScale = currentScale == null ? scale : currentScale;
        currentMarginLeft = currentMarginLeft == null ? $(this).css("margin-left") : currentMarginLeft;
        currentMarginRight = currentMarginRight == null ? $(this).css("margin-right") : currentMarginRight;

        if (scale <= 5) {
            $(this).css({ "margin-left": "200px", "margin-right": "100px" });
            scale = ('scale(' + (scale + 0.1).toString() + ')');
            $(this).css({ 'transform': scale, '-ms-transform': scale, '-webkit-transform': scale });
        }
    };

    var hammertime = Hammer(element).on("pinchin", pinchInHanlder).on("pinchout", pinchOutHandler);

    $(element).css("touch-action", "manipulation");


}

Wednesday, April 22, 2015

JavaScript - Validate Multiple Email Address

To validate multiple email address text use below JavaScript Function

Valid :
"balajisrmv@gmail.com"


function isValidEmailAddress(emailAddresses) {
    var splitter = ' ';
    var isValid = true;
    if (emailAddresses.indexOf(',') != -1)
        splitter = ',';
    else if (emailAddresses.indexOf(';') != -1)
        splitter = ';';

    var emailCollection = emailAddresses.split(splitter);

    if (emailCollection != null && emailCollection.length > 0) {
        emailCollection.forEach(function (emailAddress, index) {
            var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
            if (isValid)
                isValid = pattern.test(emailAddress.trim());
        });
    }
    return isValid;

};


Monday, April 20, 2015

JavaScript - Format URL's protocol

Formatting URL with protocol is required when we binding it to anchor tag.

For example below code anchor tag will redirect to relative path because it doesn't have protocol such as Http, Https etc.,

Below code will check protocol exist or not and add in anchor tag

function formatHttp(urlPath) {
    var urlPattern = new RegExp("^(?:f|ht)tps?://");
    if (!urlPattern.test(urlPath)) {
        urlPath = "http://" + urlPath;
    }
    return urlPath;

}



Below example shows in angularJS

HTML:

<a ng-href="{{formatHttp(someurl)}}" href="#" target="_blank"> {{someurl}} </a>

someurl is anything like without protocol "www.google.com" or with protocol "http://www.google.com", "https://www.google.com" etc.,


AngularJS Controller:

$scope.formatHttp = function (url) {
        return formatHttp(url);
};


JS File:

function formatHttp(urlPath) {
    var urlPattern = new RegExp("^(?:f|ht)tps?://");
    if (!urlPattern.test(urlPath)) {
        urlPath = "http://" + urlPath;
    }
    return urlPath;
}

Friday, December 19, 2014

AngularJS - Apply Style to currency and percentage texts before bind to UI

I have a scenario where i need to highlight currency amount values and percentage values within html text. I went over so many sites to achieve this and finally got achieved this using AngularJS with JavaScript.

What i expected is below:



What Steps i done to achive this below:

1: Create Javascript function to replace currency and percentage matched text to our required style. In this case i have used regular expression

var ReplaceCurrencyText = function (text) {
    var returnText = text.replace(/(\$?(?=\(.*\)|[^()]*$)\(?(\d{1,6}|\d{1,3},\d{3})(\.\d\d?)?\)?\%?)/g, "<span style=’color:green;’>$1</span>");
    return returnText;
};


Here $1 represents RegEx matched 1st group. Each brackets considered as one group, but in this case i used only one group (i.e., (\$?(?=\(.*\)|[^()]*$)\(?(\d{1,6}|\d{1,3},\d{3})(\.\d\d?)?\)?\%?) ).

2: Create angular directive which used to replace currency and percentage text as required

angularApp.directive('displayStyledCurrencyValue', ['$sce', function ($sce) {

    return {
        restrict: 'AE',
        replace: true,
        template:
                   '<div ng-bind-html="getStyledHtml(htmlText)"></div>',
        scope: {
            htmlText: '='
        },
        link: function (scope, element, attrs) {
            scope.getStyledHtml = function (html) {
                return $sce.trustAsHtml(ReplaceCurrencyText(html));
            };
        }
    };
}]);

Here i have used ng-bind-html to render text as html so that html element will not be shown as text and for this i used $sce.trustAsHtml method to return as html string. JavaScript function ReplaceCurrencyText called inside angular directive to get my required format of currency amount and percentage text.


3: Call this angular directive in html page wherever required and th

<display-styled-currency-value html-text="someValueToBind"></display-styled-currency-value>

Tuesday, November 25, 2014

MVC - How to get current domain root path in javaScript variable

Problem statement:

Get current domain root path in javascript variable. In some cases, we want to redirect to domain root from client side. Below is the solution for that.

Solution:

Create property in MVC model class to return current domain (Getting this in client side may occurs some url mismatches)

public class LocalMVCModel

    {
        ...etc., your other properities

        public string CurrentDomain { get { return GetSiteRoot(); } }

        private string GetSiteRoot()
        {
            string port = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
            if (port == null || port == "80" || port == "443")
                port = "";
            else
                port = ":" + port;

            string protocol = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];
            if (protocol == null || protocol == "0")
                protocol = "http://";
            else
                protocol = "https://";

            string sOut = protocol + System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + port + System.Web.HttpContext.Current.Request.ApplicationPath;

            if (sOut.EndsWith("/"))
            {
                sOut = sOut.Substring(0, sOut.Length - 1);
            }

            return sOut;

        }

        ...etc., your other properities

}



Get this property in any cshtml page as below in layout.cshtml page or in any global page

@model your.namespace.LocalMVCModel

<script type="text/javascript">
   currentDomain = '@(Model.CurrentDomain)';

</script>

or simply

<script type="text/javascript">
   currentDomain = '@(Url.Content("~"))';

</script>


 Notes:
- Razor syntax @ cannot be accessed in *.js files, so add script in cshtml page itself preferrably in layout page or some global page.
- Single quote required for razor syntax to consider as string
- Variable currentDomain in javascript can be declared anywhere in JS files and accessed here.