A day with .Net

My day to day experince in .net

Archive for the ‘Jquery’ Category

File upload and usability – Upload by a single click

Posted by vivekcek on June 26, 2016

Today i was just filing my tax via HRBlock India, and the experience was good.As you know for filing tax, you should upload your Form 16 docs to Hrblock.
They provide the below screen for uploading each document.Here you need to select each document and click the upload button, that is 2 click per upload.

Can we change this to single click, No i think because we may need to provide password for each file, if present.
So this screen is valid.

1

In some other sites , i have seen you have to do 2 mouse click for an upload.Normally developers design a file upload like below, a file browse input and upload button.

3

So how we can save one click, with just a single button click.

4

For that you can use bootstrap and jquery.

First add this style to your page.

<style type="text/css">
    .btn-file {
        position: relative;
        overflow: hidden;
    }

        .btn-file input[type=file] {
            position: absolute;
            top: 0;
            right: 0;
            min-width: 100%;
            min-height: 100%;
            font-size: 100px;
            text-align: right;
            filter: alpha(opacity=0);
            opacity: 0;
            outline: none;
            background: white;
            cursor: inherit;
            display: block;
        }
</style>

Place your input control via below code snippet.

<span class="btn btn-default btn-file">
    Upload Files <input type="file">
</span>

Use the below script to upload.

@section scripts
{
    <script type="text/javascript">
        $(document).ready(function () {
            $(document).on('change', '.btn-file :file', function () {
                var input = $(this);
                var files = input.get(0).files;
                if (files.length > 0) {
                    var data = new FormData();
                    for (i = 0; i < files.length; i++) {
                        data.append("file" + i, files[i]);
                    }
                    input.trigger("onclick");//Please keep this to fire the change event next time
  
                    $.ajax({
                        type: "POST",
                        url: "",
                        contentType: false,
                        processData: false,
                        data: data,
                        global: false,
                        success: function (response) {

                        },
                        error: function () {

                        }
                    });

                }
            });

            $(document).on('onclick', '.btn-file :file', function () {
                this.value = null;
            });
        });
    </script>
}

Posted in Jquery, MVC, SignalR | Tagged: , , , , | Leave a Comment »

Auto-complete with MVC 4 and Jquery

Posted by vivekcek on May 28, 2013

1. Refer required CSS and Jquery libraries(jquery,jquerui)

2. Implement a controller action like this

public JsonResult Search(string term)
        {
            List<Movie> Movies = new List<Movie> {new Movie(){ Title="Transformer", ReleaseYear=2008},
            new Movie(){ Title="Titanic", ReleaseYear=2008},
            new Movie(){ Title="Predator", ReleaseYear=2008},
            new Movie(){ Title="Men in blck", ReleaseYear=2008},
            new Movie(){ Title="Terminator", ReleaseYear=2009},
            new Movie(){ Title="Indiana jones", ReleaseYear=2009},
            new Movie(){ Title="Life is beautiful", ReleaseYear=2009},
            new Movie(){ Title="jurasic park", ReleaseYear=2007},
            new Movie(){ Title="Luck", ReleaseYear=2007},
            };

            var movies = Movies.Where(x => x.Title.StartsWith(term)).Select(r => new {label=r.Title });
            return Json(movies, JsonRequestBehavior.AllowGet);
        }

Please note that parameter name should be ‘term‘. And returned json result should contain a ‘label‘ attribute.

3. Now write the below script in your page.

$(function () {
    $('#SearchBox').autocomplete({
        source: '/Home/Search'
    });
});

Posted in Jquery, MVC | Leave a Comment »

Jquery Reference Part2

Posted by vivekcek on December 25, 2012

1. Each function in jquery.

The below function take all the div’s with specified classes and iterate through them.

$('div.BlueDiv,div.RedDiv').each(function (index) {
alert(index + '=' + $(this).text());
});

2. Modify attribute of a div by raw DOM object and Jquery wrapped object.

$('div').each(function (i) {
this.title = "hai"; //raw dom object not jquery object so no intellisense
$(this).attr('title', 'title2'); //jquery objcet wrpped with $ with intellisense
            });

3. Set font size of all div.

 $('div').css('font-size', '20px'); //automatic iteration

4. JSON Map and Chaining with jquery

 $('div').attr(
                    {
                        title: 'titile 4',
                        style: 'font-size:40px;background-color:yellow'  //JSON MAP
                    }
                )
            .css('color', 'Red'); //Chaining

5.Append table to a div.

$('#OutPutDiv').append('<table><tr><td style="font-size:50px">AppendChild</td></tr></table>');

6. wrap a div.

$('#OutOutDiv').wrap('<div style="font-size:40px"></div>'); //wraps outputdiv inside wrap

7. Remove div.

$('#OutOutDiv').remove();

8. addClass,hasClass,removeClass,JSON map Css

 $('#OutPutDiv').css({
                'background-color': 'Navy',
                'color':'White'
            });

            $('#TestDiv').addClass('HighLight');
            $('div').removeClass('class1 class2');
            if ($('#TestDiv').hasClass('HighLight'))
            {}

Posted in Jquery | Leave a Comment »

Jquery Reference Part1

Posted by vivekcek on December 25, 2012

1. How to start with jquery?

Download the latest jquery file and save it in folder. Refer this file by

<script type="text/javascript" src="Scripts/jquery-1.7.1.js"></script>

Now add a script tag with document.ready() function.

<script type="text/javascript">
        $(document).ready(function () {
            //code here
        });
    </script>

document.ready() function executed when the DOM is ready. Fire before the images are loaded

2. Select all div using jquery.

var divs = $('div');//by tag name
alert(divs.length);

3. Iterate through all div

 $('div').each(function () {
                alert($(this).html());
            });

4. Get all div and span elements

 var divspans = $('div,span');
 alert(divspans.length);

5.Get Div by id

alert($('#TestDiv').html());

6. Get div by css class

var divclss = $('.BlueDiv');
var divclss = $('div.BlueDiv'); //fast

7. Change css

$('.BlueDiv').css('border', '2px solid red');

8. Get all div with a title attribute

var divTtile = $('div[title]');
alert(divTtile.length());

9. Get all dive with title attribute value ‘test’

var divWithTitle = $('div[title="test"'); //case sensitive
alert(divWithTitle.length);

10. Get all input tag

var inputs = $(':input');
alert($(inputs[2]).val());


11. Table row coloring with jquery

 $('tr:odd').css('background-color', 'Green');
 $('tr:even').css('background-color', 'Red');
 //speacial effect to first child
 $('tr:first-child').css('background-color', 'Navy');
 //table id given
 $('#mytable tr:odd').css('background-color', 'Yellow');

12. Start with, end with, contains

alert($('div[title$="india"').html()); //ends with
alert($('div[title^="india"').html()); //start with
alert($('div[title*="india"').html()); //some where contains with

Posted in Jquery | Leave a Comment »

Load data dynamically on page scroll using jquery,ajax and asp.net.

Posted by vivekcek on March 11, 2012

Introduction

In Facebook you might saw status updates of your friends are dynamically loaded when you scroll the browser’s scroll bar. So in this article i am going to explain how we can achieve this using jQuery and Ajax.

Using the code

The solution includes 2 web forms(Default.aspx and AjaxProcess.aspx). The Default.aspx contain a Div with ID “myDiv“. Initially the Div contain some static data, then data is dynamically appended to the Div using jquery and ajax.

<div id="myDiv">
	<p>Static data initially rendered.</p>
</div>

The second Web Form AjaxProcess.aspx contains a web method GetData(), that is called using ajax to retrieve data.

[WebMethod]
    public static string GetData()
    {
        string resp = string.Empty;
        resp += "<p>This content is dynamically appended to the existing content on scrolling.</p>";
        return resp;
   }

Now we can add some jquery script in Default.aspx, that will be fired on page scroll and invoke the GetData()method.

 $(document).ready(function () {

            $(window).scroll(function () {
                if ($(window).scrollTop() == $(document).height() - $(window).height()) {
                    sendData();
                }
            });

            function sendData() {
                $.ajax(
                 {
                     type: "POST",
                     url: "AjaxProcess.aspx/GetData",
                     data: "{}",
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                     async: "true",
                     cache: "false",

                     success: function (msg) {
                         $("#myDiv").append(msg.d);
                     },

                     Error: function (x, e) {
                         alert("Some error");
                     }

                 });

            }

        });

Here, to check whether the scroll has moved at the bottom, the following condition is used.

 $(window).scroll(function () {
                if ($(window).scrollTop() == $(document).height() - $(window).height()) {
                    sendData();
                }
            });

This condition will identify whether the scroll has moved at the bottom or not. If it has moved at the bottom, dynamic data will get loaded from the server and get appended to myDiv.

success: function (msg) {
                         $("#myDiv").append(msg.d);
                     },

Download Code

https://skydrive.live.com/redir.aspx?cid=12c9d813342f227a&resid=12C9D813342F227A!126&parid=12C9D813342F227A!120&authkey=!AJIbc1495KJup70

Posted in Jquery | Tagged: , , | 3 Comments »