Get Asp.Net TextBox or Label value using JQuery

If you have a Asp.Net TextBox or Label then you can get the value of that textbox/label using Jquery.

Get TextBox value with jquery:


Lets say you have a asp.net textbox like below

<asp:TextBox ID="txtName" runat="server" />

then you can get the value of the above textbox using JQuery using the below code

var name = $("#<%=txtName.ClientID %>").val();

Get Label value with jquery :


Lets say you have a asp.net label like below

<asp:Label ID="lblName" runat="server" Text="codeSolver"/>

then you can get the value of the above label using JQuery using the below code

var name = $("<%=lblName.ClientID %>").html();

Note: If you notice the selector in the above code, we are using "ClientID" to get the value of the control. This is because Asp.Net controls are rendered as html controls in the browser. The "id" will be not same as what you have given to that control.

So if you simply write $("#txtName") it won't work. We use that syntax to get the value of a HTML input(type="text") element.

In this way we can get the Asp.Net TextBox or Label values using JQuery.

For more posts on JQuery visit: JQuery

Read more...

Get Asp.Net TextBox or Label value using JavaScript

If you have a Asp.Net TextBox or Label then you can get the value of that textbox/label using javascript.

Get TextBox value:


Lets say you have a asp.net textbox like below

<asp:TextBox ID="txtName" runat="server" />

then you can get the value of the above textbox using javascript using the below code

var name = document.getElementById("<%=txtName.ClientID %>").value;

Get Label value :


Lets say you have a asp.net label like below

<asp:Label ID="lblName" runat="server" Text="codeSolver"/>

then you can get the value of the above label using javascript using the below code

var name = document.getElementById("<%=lblName.ClientID %>").innerHTML;

Note: If you notice the selector in the above code, we are using "ClientID" to get the value of the control. This is because Asp.Net controls are rendered as html controls in the browser. The "id" will be not same as what you have given to that control.

So if you simply write getElementById("txtName") it won't work. We use that syntax to get the value of a HTML input(type="text") element.

In this way we can get the Asp.Net TextBox or Label values using javascript.

For more posts on Javascript visit: javascript

Read more...

Check or Uncheck all checkboxes with master checkbox in jquery

In many sites you have seen this situation(example: in Gmail) where checking the master checkbox should check all the other child checkboxes or unchecking the master checkbox should uncheck all the other child checkboxes. So, in this post we are going to see how we can do this using JQuery.

Checking the all checkboxes when the header checkbox is checked


Lets create a group of checkboxes

<input type="checkbox" id="headerCheckbox"/>
 
    <input type="checkbox" class="childCheckBox" id="Checkbox1"/>
    <input type="checkbox" class="childCheckBox" id="Checkbox2"/>
    <input type="checkbox" class="childCheckBox" id="Checkbox3"/>
    <input type="checkbox" class="childCheckBox" id="Checkbox4"/>
    <input type="checkbox" class="childCheckBox" id="Checkbox5"/>
    <input type="checkbox" class="childCheckBox" id="Checkbox6"/> 

We have created a header checkbox and some child checkboxes. We have used same class(class="childCheckBox") for all the child checkboxes which are related to the header checkbox. Now, if we check the header checkbox all the child checkboxes should be checked.

For that, use the below JQuery code

$('#headerCheckbox').click(function () {
    var isheaderChecked = this.checked;
    $(".childCheckBox").each(function () {
        this.checked = isChecked;
    })
})

The above code will check all checkboxes with the class "childCheckBox" and also if you uncheck the header checkbox then all the child checkboxes will be unchecked.

Unchecking the header checkbox when any one of the child checkbox is unchecked


When you uncheck any one of the child checkbox then the header checkbox should also be unchecked. For that case use the following JQuery code

$("input[type='checkbox']:not(:first)").click(function () {
    var allChecked = true;
    $("input[type='checkbox']:not(:first)").each(function () {
        if (this.checked == false) {
            allChecked = false;
            $('#headerCheckbox').prop('checked'false);
        }
    })
    if (allChecked == true) {
        $('#headerCheckbox').prop('checked'true);
    }
})

In this way you can check or uncheck all the checkboxes when a master checkbox is checked.

For more posts on Jquery please visit: JQuery

Read more...

How to Set/Get the textbox value using JQuery/Javascript

If you have a textbox, then you can get the value of the textbox or you can set the value of the textbox using JQuery.

Example:

Lets say you have a textbox like below

First Name:<input type="text" id="txtFirstName" />

JQuery code to get textbox value

var value=$('#txtFirstName').val();

Javascript code to get textbox value

var Firstname = document.getElementById('txtFirstName').value;

JQuery code to set textbox value

$('#txtFirstName').val("your name");

Javascript code to to set textbox value

document.getElementById('txtFirstName').value = "your name";

In this way you can set/get textbox value using jquery/javascript.

For more posts on Javascript/JQuery visit: jquery


Read more...

Dynamically apply a class using AngularJS

Angular provides ng-class directive for adding/removing css styles dynamiucally.

According to angular docs: The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.

ng-class accepts an "expression" that must evaluate to one of the following:

1.a string of space-delimited class names
2.an array of class names
3.a map/object of class names to boolean values

Lets say you are showing a list of items using ng-repeat and each item has a corresponding checkbox. Now when a checkbox is checked then you want to apply some styles to that respective item (like changing the color etc). This can de done using ng-class. Look at the below code to see how it works.

Example:

html code:

<div ng-controller="MyCtrl">
    <div ng-repeat="item in items" ng-class="{'selected-item': item.checked}">
        <input type="checkbox" ng-model="item.checked">
        {{item.name}}{{item.title}}
    </div>
</div>

javascript:

var myApp = angular.module('myApp', []);
 
function MyCtrl($scope) {
    $scope.items = [
        {
            name: 'Misko',
            title: 'Angular creator'
        },
        {
            name: 'Igor',
            title: 'Meetup master'
        },
        {
            name: 'Vojta',
            title: 'All-around superhero'
        }
 
    ];
}

css:

.selected-item {
    colorgreen;
}


When you click on a checkbox, the class "selected-item" gets added to the particular item and the color will be changed to green as mentioned in css.

For live example look at this fiddler: http://jsfiddle.net/codingsolver/dxBdR/

Note: If a class was already applied then the directive will not add duplicate class. When expression changes , newly added classes will be removed.

This way we can add css classes dynamically using AngularJS.

For more posts on AngularJS visit: AngularJS
Read more...

Copy code from visual studio to blogger

If you have a blog and if you are writing posts which contains code(html/css/javascript/c# etc), then you may want to show that code on your blog just like how you see it in visual studio. But if you directly copy & paste your code from visual studio to your blogger, it won't work.

You can use  Visual Studio Productivity Power Tools.  The traditional VS copies the plain text to clipboard. But after installing the above extension copying will place the formatted and colorized HTML fragment on clipboard.

How to install :

Download the extension from the following links

for VS 2010http://visualstudiogallery.msdn.microsoft.com/d0d33361-18e2-46c0-8ff2-4adea1e34fef/

for VS 2012http://visualstudiogallery.msdn.microsoft.com/3a96a4dc-ba9c-4589-92c5-640e07332afd

download and install the extension.

After installing, restart the Visual Studio then copy the code and paste it in blogger. That's it.  It's working fine..

Happy Blogging..  :-)

Read more...

AngularJs directive for Image Cropping

Whenever we are allowing a user to upload images, it's better to provide cropping option for them. So, today we will discuss about the AngularJs directive which allows users to crop image before saving it.

For that you need to use JQuery's JCrop plugIn in your project. You can download it from https://github.com/tapmodo/Jcrop . Download the zip from the above link and add jquery.jcrop.js and jquery.jcrop.css files to your project.

<script src="scripts/jquery.min.js" type="text/javascript">
</script>
<script src="scripts/jquery.Jcrop.js" type="text/javascript">
</script>

<link href="css/jquery.Jcrop.css" rel="stylesheet" type="text/css">

Now add the following angularjs directive in your javascript file
app.directive('imgCropped'function () {
    return {
        restrict: 'E',
        replace: true,
        scope: { src: '@', selected: '&' },
        link: function (scope, element, attr) {
            var myImg;
            var clear = function () {
                if (myImg) {
                    myImg.next().remove();
                    myImg.remove();
                    myImg = undefined;
                }
            };
 
            scope.$watch('src'function (nv) {
                clear();
                if (nv) {
                    element.after('<img />');
                    myImg = element.next();
                    myImg.attr('src', nv);
                    $(myImg).Jcrop({
                        trackDocument: true,
                        onSelect: function (x) {
                            scope.$apply(function () {
                                scope.selected({ cords: x });
                            });
                        },
                        aspectRatio: 1
                    }, function () {
                        // Use the API to get the real image size 
                        var bounds = this.getBounds();
                        boundx = bounds[0];
                        boundy = bounds[1];
                    });
                }
            });
            scope.$on('$destroy', clear);
        }
    };
});

Now add the following html code in body section
<div ng-controller="MainCtrl">
    <img-cropped src='http://deepliquid.com/Jcrop/demos/demo_files/pool.jpg' selected='selected(cords)'></img-cropped>
    <div ng-show="cropped" id="cropped-image-container">
        <img id="preview" src='http://deepliquid.com/Jcrop/demos/demo_files/pool.jpg'>
    </div>
</div>
add the following custom styles to your style sheet
div#cropped-image {
    height150px;
    width150px;
    overflowhidden;
}

In the above HTML we are using a image to crop and a div which contains the cropped image. So, if we start cropping the original image, the new cropped image is showed in the div. (see this plnkr for live example: angularjs directive for image cropping )

Now add the following controller to your javascript file
app.controller('MainCtrl'function ($scope) {
    $scope.selected = function (cords) {
        $scope.cropped = true;
        var rx = 150 / cords.w;
        var ry = 150 / cords.h;
        $('#preview').css({
            width: Math.round(rx * boundx) + 'px',
            height: Math.round(ry * boundy) + 'px',
            marginLeft: '-' + Math.round(rx * cords.x) + 'px',
            marginTop: '-' + Math.round(ry * cords.y) + 'px'
        });
    };
});

When a user crops the image, the "selected" function inside the "MainCtrl" gets called which gets the cropped image's co-ordinates. Now using that co-ordinates we are applying css styles to the preview image(which is in the second div).

That's it. Here JCrop doesnot creates a new image , instead it just gives you the cropped image's co-ordinates. Using that co-ordinates you have to change the css of the image. See this stackoverflow question for more details about saving the cropped image to database. save cropped image - jcrop

Hope it helps you. Happy coding :-) :-)

For more articles on AngularJs visit: AngularJs


Read more...

AngularJs Directive for notifications

When ever we are building a webpage we may want to show some notification messages to the users. Here we are going to use JQuery's miniNotiication plugIn to show notifications. You can download this plugin from here: https://github.com/miniJs/miniNotification

download the zip file and add the miniNotification.js file to your project.

Add the following service to your services.js file.

app.factory('NotificationService', ['$rootScope', function ($rootScope) {

    var notificationService = {

        information: function (message) {
          $rootScope.$broadcast("notificationBroadcast", { "Message": message, "Type": 'information' });
        },

        success: function (message) {
          $rootScope.$broadcast("notificationBroadcast", { "Message": message, "Type": 'success' });
        },

        error: function (message) {
          $rootScope.$broadcast("notificationBroadcast", { "Message": message, "Type": 'error' });
        }
    };
    return notificationService;
}]);


we are going to call this service in our controllers whenever we want to show notifications. There are three types of notifications in the service.

1.Notification of type "information"
2.Notification of type "success"
3.Notification of type "error"

And now add the following directive to your directives.js file

app.directive('PostDataNotification', function () {

    return function (scope, element, attrs) {
        scope.$on('notificationBroadcast', function (event, args) {
            scope.notificationMessage = args.Message;
            $('.notification').miniNotification({ time: 3000 });
        });
    };

});


The html code to show the notification

  <div class="notification" post-data-notification="">
            <p>{{notificationMessage}}</p>
   </div>


we are using the "PostDataNotification" directive on the div. Inside the directive we are adding some text to  "notificationMessage".

Now we need to add some styles to notification div. (change the styles as per your requirement)

.notification {
    display: none;
    position: fixed;
    cursor: pointer;
    width: 100%;
    background: #EFEFEF;
    text-align: center;
    z-index: 9999;
    padding: 9px;
    padding-left: 0px;
}

    .notification p {
        font-size: 14pt;
        font-family: 'Segoe UI','Arial';
        margin-top: 5px;
        margin-bottom: 5px;
    }


We are almost done. The last thing is calling the service from our controller.

If you want to show a success notification when a record is saved to database. Then you just call the notificationsService from success function of the ajax/http call.

Example:

        $.ajax({
                type: "POST",
                url: serviceURL,
                data: "",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: successFunc,
                error: errorFunc
            });

            function successFunc(data, status) {    
                     NotificationService.success('successfully added data');
            }

            function errorFunc() {
                      NotificationService.error('Error in adding data');
            }
        });


Here we are calling NotificationService which calls Notification directive (using $broadcast and $on).

Hope it helps you.

For more posts on JQuery visit: JQuery

For more posts on AngularJs visit: AngularJS

Read more...

AngularJS Blur Directive

There is no direct support for blur event in AngularJs. But we can add support for blur event by creating directive.

Add the following directive to your javascript file

app.directive('ngBlur', ['$parse', function($parse) {
  return function(scope, element, attr) {
    var fn = $parse(attr['ngBlur']);
    element.bind('blur', function(event) {
      scope.$apply(function() {
        fn(scope, {$event:event});
      });
    });
  }
}]);

Then use it in your html template like below

<input type="text" ng-blur="myFunc()"/>

And write the function myFunc() in your controller

$scope.myFunc = function(){
   alert("hello!!");
}

Hope this helps you.

For more posts on AngularJs visit: http://coding-issues.blogspot.in/search/label/angularJS

Read more...