Showing posts with label jQuery Codes. Show all posts
Showing posts with label jQuery Codes. Show all posts

Thursday, August 14, 2014

How to copy text from one input textbox to multiple textboxes using jQuery

In this post, find jQuery code to copy text from one input textbox to multiple textboxes while typing or in real time or on paste. To achieve this, give a same class name to all the textboxes in which text needs to be copied.

For example, in the below code all the textboxes are having same class named "copyText".
<input type='text' id='txtFirst' class='copyText' /><br/>
<input type='text' id='txtSecond' class='copyText' /><br/>
<input type='text' id='txtThird' class='copyText' /><br/>
Now, attach "keyup", "change" and "paste" event on "copyText" class and then assign the current input value to all other textboxes.
$(document).ready(function(){
    $('.copyText').on('keyup change paste', function(e){
        $('.copyText').val($(this).val())
    });
});
You may also like:
Above code will keep all the textboxes in sync. But if you want to copy text from first input to all others not vice-versa then attach "keyup", "change" and "paste" event on first input text only.
$('#txtFirst').on('keyup change paste', function(e){
     $('.copyText').val($(this).val())
 });
See Complete Code
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, August 7, 2014

How to Limit Number of Characters in Textarea using jQuery

Find jQuery code to limit characters inside textarea control. Below code also handles copy + paste and on drop event.
$(function () {
    var nMaxLength = 150;
    $("#txtDesc").keydown(function (event) {
        LimitCharacters($(this));
    });
    $("#txtDesc").keyup(function (event) {
        LimitCharacters($(this));
    });

    function LimitCharacters(txtDesc) {
        if (txtDesc.val().length > nMaxLength) {
            txtDesc.val(txtDesc.val().substring(0, nMaxLength));
        } else {
            var nRemaining = nMaxLength - txtDesc.val().length;
            $('.remaining').text(nRemaining);
        }
    }
});
To stop drag and drop in textarea, simply set onDrop="return false;".
<textarea name="txtDesc" rows="4" cols="50" id="txtDesc" onDrop="return false;" style="width:70%;"></textarea>
You may also like: Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, June 10, 2014

Detect IE11 using JavaScript/jQuery

In this post, find JavaScript/jQuery code to detect IE 11. Your old code detect IE browser either using navigator.userAgent or $.browser.msie will not work for IE 11 as the User Agent string for IE 11 is changed.

Previously I had posted about Detect Browsers using jQuery, but with the release of jQuery 1.9 $.browser feature was removed. But to support legacy code, they have released jQuery Migrate plugin to detect deprecated and removed features, or to restore old features for those sticky situations where you need old code to run with new jQuery. You can read more about How to migrate older jQuery code to jQuery 1.9+

You may also like:
The user agent string for IE11 on Windows 8.1 is,
Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko
And if you compare with earlier version of IE then you will find the "MSIE" token is no longer present. For the earlier version of IE, "MSIE" token was present. Take a look at IE10 user agent string.
Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)
So the code to find index of "MSIE" in navigator.userAgent will not work for IE11.
var sAgent = window.navigator.userAgent;
var Idx= sAgent.indexOf("MSIE");
So to detect IE11, all you need is to look for "Trident/7.0" in user agent string. Here is updated code to detect all versions of IE including IE 11.
function GetIEVersion() {
  var sAgent = window.navigator.userAgent;
  var Idx = sAgent.indexOf("MSIE");

  // If IE, return version number.
  if (Idx > 0) 
    return parseInt(sAgent.substring(Idx+ 5, sAgent.indexOf(".", Idx)));

  // If IE 11 then look for Updated user agent string.
  else if (!!navigator.userAgent.match(/Trident\/7\./)) 
    return 11;

  else
    return 0; //It is not IE
}

if (GetIEVersion() > 0) 
   alert("This is IE " + GetIEVersion());
else 
   alert("This is not IE.");
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, May 27, 2014

jQuery on() - Click event not working for dynamically added element

My colleague got stuck into a problem where he was using jQuery on() method to attach the click event handlers but click event was not working for dynamically added elements. Although he knew that .bind() method doesn't work for dynamically added element but he was quite sure about .live() and .on(). Since .live() method is already deprecated, so .on() method was the only left choice.

But for him even the .on() was working for one of his scenario. First let's see the scenario. There is a HTML table with set of rows and every row with class "trDummy" being added dynamically.
<table class="tbMain">
  <tr class="trDummy">
     <td>Some Data</td>
     <td><a href="#" class="toggle">Close</a></td>
  </tr>
</table>
And there was a close event attach to "tr" using .on() which does blah blah..
$(document).ready(function () {
  $('.trDummy').on('click', '.close', function () {
     //Do something...
  });
});
The close event was working fine for already added "tr" but it was not working for dynamically added "tr" rows. Is there anything wrong?
YES, there is. Official jQuery document about jQuery on() says,

" Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."

So click event works only for element present on the page. If it is added dynamically, it's not going to work. So, the solution is to delegate the events to that wrapper, instead of binding handlers directly on the dynamic elements. So always use static elements in which you add the dynamic control while using .on().
$(document).ready(function () {
  $('.tbMain').on('click', '.close', function () {
     //Do something...
  });
});
Related Post: Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, April 15, 2014

Export table to Excel using jQuery in IE

Previously I had posted about Export table data to Excel using jQuery but that solution doesn't work in IE. And many of us are looking for solution to this problem. If you are using ASP.NET, then by end of this post you will have the solution.

To make it work for IE with ASP.NET, we need to append header in Response object and then allow downloading of file. This can't be done only on client side for IE. So the idea is to pass the table data along with its structure to ASP.NET server side code and then using server side code, allow downloading of file. But before passing the data to server, escape the HTML tags to handle "A potentially dangerous Request. Form value was detected from the client" exception.

Below jQuery code attaches click handler to button and escapes the data and assign it to a hidden field. The same hidden field will be accessed at server side to get the escaped table structure.
$(document).ready(function () {
    $("#btnExport").on('click', function (e) {
          var tblHTML = $("#dvData").html();
          tblHTML = escape(tblHTML);
          $('#hdnData').val(tblHTML);
   });
});
And below is ASP.NET server side button click code, which adds header to Response object and defines the content type to "application/excel". And then writes the data.
protected void btnExport_Click(object sender, EventArgs e)
 {
   string data = hdnData.Value;
   data = HttpUtility.UrlDecode(data);
   Response.Clear();
   Response.AddHeader("content-disposition", "attachment;filename=Data.xls");
   Response.Charset = "";
   Response.ContentType = "application/excel";
   HttpContext.Current.Response.Write(data);
   HttpContext.Current.Response.Flush();
   HttpContext.Current.Response.End();
}
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, March 25, 2014

jQuery: Convert ASP.NET GridView Data into CSV

In this post, find jQuery code to convert ASP.NET GridView data into CSV format which is sometimes quite useful for exporting purpose. This can be also be done using server side code but that involves extra overhead "postback".

ASP.NET GridView control is rendered in table > th > tr > td format. The columns names are placed in th tag and all the data goes into various td tags. Also refer ebook on ASP.NET GridView & jQuery Tips and Tricks.


You may also like:

To create CSV, we need to loop through GridView including header and rows. While iterating, store the value in a array and in the end join the array with "," sign to form CSV.
$(document).ready(function() {
   $("#<%=txtCSV.ClientID%>").hide();
   $('#<%=btnSubmit.ClientID%>').click(function(e)
   {
     var arrCSV = [];
     var strTemp = '';
     $("#<%=gdRows.ClientID%>").find("tr").each(function () 
     {
       if ($(this).find("th").length) 
       {
         var arrHeader = [];
         $(this).find("th").each(function () {
           strTemp = $(this).text().replace(/"/g, '""');
           arrHeader.push('"' + strTemp + '"');
         });
       arrCSV.push(arrHeader.join(','));
      }
      else 
      {
        var arrData = [];
        $(this).find("td").each(function () {
         strTemp = $(this).text().replace(/"/g, '""');
         arrData.push('"' + strTemp + '"');
       });
       arrCSV.push(arrData.join(','));
      }
   });

    var strCSV = arrCSV.join('\n');
    $("#<%=txtCSV.ClientID%>").val(strCSV);
    $("#<%=txtCSV.ClientID%>").show();
    e.preventDefault();
   });
});
If you don't want to include headers in your CSV, then you can remove below code block from above code.
if ($(this).find("th").length) 
{
   var arrHeader = [];
   $(this).find("th").each(function () {
     strTemp = $(this).text().replace(/"/g, '""');
     arrHeader.push('"' + strTemp + '"');
   });
   arrCSV.push(arrHeader.join(','));
}
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, January 7, 2014

How to restore CSS styles using jQuery

To assign inline css to any DOM element, we can jQuery ".css()" method to define it. Like,
$("#dvText").css('color','#FF0000');
And if you need to remove the color again, then you can use the same css method to remove it. Like,
$("#dvText").css('color','');
The above method to remove/restore the style is fine, when you have defined a single inline css class. If you have defined multiple CSS styles like,
$(document).ready(function(){
  $("#dvText").css('background-color','#FFFF00');
  $("#dvText").css('color','#FF0000');
  $("#dvText").css('font-family','Arial');
  $("#dvText").css('font-size','18pt');
});
Or using CSS method to combine multiple CSS styles.
$("#dvText").css({
  'background-color':'#FFFF00',
  'color':'#FF0000',
  'font-family':'Arial',
  'font-size':'18pt'})
In this case, you need to write same number of statement to remove/restore all the CSS styles which defined earlier. Is there any simple and slick way to do this?

Yes, there is. But first understand what actually .css() method does. When .css() method is used, it defines a style attribute to the DOM element. For example,
$("#dvText").css('color','#FF0000');
will be equivalent to:
<div style="color:#FF0000;">...</div>
So, to remove/restore all the defined style attribute, all you need to do is to remove style attribute which you can do via "removeAttr()" method.
$("#dvText").removeAttr("style") ;
Read more...

Wednesday, October 30, 2013

Fix for ASP.NET Checkbox -jQuery click event getting fired twice issue

This is really interesting. If ASP.NET checkboxes or checkbox list is placed within any container element like div or span, and click event is attached on checkbox. And then clicking on checkbox text will call click event twice. For example, consider the following HTML/ASP.NET code.
<div id="dvList">
<asp:CheckBox ID="chk1" runat="server" Text="Check1" CssClass="Dummy" /> 
<asp:CheckBox ID="chk2" runat="server" Text="Check2" CssClass="Dummy" /> 
</div>
Now using jQuery, bind click event to all the checkboxes which are child element of div element with ID "dvList".
$(document).ready(function(){
   $('#dvList').find('.Dummy').on('click',function(){
      alert('Test');
   });
});
If checkbox is clicked, then alert will come only once. But if click is made on text associate with checkbox, then alert will be displayed twice. Surprise!!! This is happening due to event bubbling. Before moving to event bubbling it is important to understand how checkbox is rendered in browser. A single ASP.NET checkbox,
<asp:CheckBox ID="chk1" runat="server" Text="Check1" CssClass="Dummy" /> 
is rendered in browser like,
<span class="Dummy">
   <input id="chk1" type="checkbox" name="chk1" />
   <label for="chk1">Check1 </label>
</span>
In above jQuery code, though we have setup click event handler for elements with class "Dummy" only but all the child elements also get wired to click event. We have set up a click event handler for both the <label> and the <input> and <span class="Dummy"> elements. So clicking on the <label>, the click event handler that on the label will execute, and then the click event handler set up on the <input> will execute as the label raises the click event on the <input> as well. This is exactly what event bubbling is.

To stop event bubbling, jQuery provides a method "stopPropagation()". See below jQuery code.
$(document).ready(function () {
   $('#dvList').find('.Dummy').on('click', function (evt) {
     alert('Test');
     evt.stopPropagation();
     evt.preventDefault();
  });
});
With this code, you will see alert appearing only once when you click on text but you will find that checkbox status is not getting updated. Which is due to
So, now what is the solution. Well, the solution is to first identify the element which was clicked. Whether its <label> or <span>. If its <label> or <span> then the click event will be fired twice. As explained earlier, click event first gets fired for the <label> or <span> and second time for <input>. So for the first trigger, we should simply ignore the click event by checking event target. And for next trigger, the source will be <input> so alert is fired.
$(document).ready(function(){
   $('#dvList').find('.Dummy').on('click',function(evt){
      var target = evt.target.tagName.toUpperCase();
      if (target === "LABEL" || target === "SPAN") { 
         return;
      }
      alert('Test');
   });
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, August 20, 2013

jQuery - Page Redirect after X seconds wait

You must have come across any website which uses a webpage with some annoying advertisement and a message that says "You will be redirected to actual page after X seconds". This can be easily implemented with jQuery. In this post, find jQuery code to redirect user to another webpage after specific time interval or few seconds.

Related Post:
The below jQuery code uses JavaScript setInterval which executes a function, over and over again, at specified time intervals. So all is required is to set the setInterval as 1 second and then minus the counter from actual time interval. When it reach to zero second , simply redirect to specific path.
$(document).ready(function () {
   window.setInterval(function () {
      var iTimeRemaining = $("#spnSeconds").html();
      iTimeRemaining = eval(iTimeRemaining);
      if (iTimeRemaining == 0) {
         window.location.href = "http://jquerybyexample.blogspot.com/";
      }
      else {
         $("#spnSeconds").html(iTimeRemaining - 1);
      }
  }, 1000);
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Wednesday, July 24, 2013

jQuery: Restrict occurrence of specific word in textbox

Below jQuery code allows to restrict user to enter any specific word only once in textbox. For demo, I have used "article" word and it should occur only once in textbox. The code also makes case insensitive search.
$(document).ready(function () {
    $('#txtDesc').bind('keyup', function () {
        var txtToMatch = /article/gi;
        var iLimit = 1;
        var sMatch = $(this).val().match(txtToMatch);       
        if (sMatch !== null && sMatch.length > iLimit) {
            $(".error").html("The word 'article' can occur only once.");
        } else {
            $(".error").html("");
        }
    });
});
Related Post:
If you want to make case sensitive search then, change "/article/gi" to "/article/g".
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, July 23, 2013

Detect Scroll Position (Up/Down) using jQuery

Below jQuery code detects whether user is scrolling up or down in the webpage.
var iScrollPos = 0;

$(window).scroll(function () {
    var iCurScrollPos = $(this).scrollTop();
    if (iCurScrollPos > iScrollPos) {
        //Scrolling Down
    } else {
       //Scrolling Up
    }
    iScrollPos = iCurScrollPos;
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, July 22, 2013

jQuery: Select all readonly input type textbox

In this short post, find jQuery code to select all readonly input type textboxes present on the page.
$(function(){
    $(":input[type=text][readonly='readonly']").val("");
});
However, if you have single readonly textbox element, then select it using its ID. And if you want to exclude all readonly input type textboxes from selection, then use below jQuery code.
$(function(){
    $(":input[type=text]:not([readonly='readonly'])").val("");
});
The only difference is that ":not" selector is used to exclude readonly input type elements.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, July 4, 2013

jQuery: How to Strip/Remove HTML tags

In this short post, find jQuery code to strip/remove HTML tags. To remove HTML tags, use text() function which returns only the text content and ignores the HTML portion.
console.log($('#dvTest').text());
You can also strip/remove HTML tags from any variable as well as text() is jQuery function, so the variable needs to be converted into a jQuery object so that text() can be used.
var str = '<div>Sample <u>HTML</u> <b>Text</b> with <i>tags</i></div>';
console.log($(str).text());
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, June 18, 2013

jQuery to redirect page after specific time interval

You must have come across any website which uses a webpage with some annoying advertisement and a message that says "You will be redirected to actual page after X seconds". This can be easily implemented with jQuery. In this post, find jQuery code to redirect user to another webpage after specific time interval or few seconds.

The below jQuery code uses JavaScript setInterval which executes a function, over and over again, at specified time intervals. So all is required is to set the setInterval as 1 second and then minus the counter from actual time interval. When it reach to zero second , simply redirect to specific path.

Related Post:
$(document).ready(function () {
   window.setInterval(function () {
      var iTimeRemaining = $("#spnSeconds").html();
      iTimeRemaining = eval(iTimeRemaining);
      if (iTimeRemaining == 0) {
         window.location.href = "http://jquerybyexample.blogspot.com/";
      }
      else {
         $("#spnSeconds").html(iTimeRemaining - 1);
      }
  }, 1000);
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, June 13, 2013

Check for '#' hash in URL using jQuery

In this short post, find jQuery code to check if URL contains "#" (hash) or not. This can be checked via location.hash property provided by JavaScript and same can be used in jQuery.
$(document).ready(function(){
    if(window.location.hash) {
      // # exists in URL
    } 
    else {
       // No # in URL.
    }
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Friday, June 7, 2013

Get Client IP address using jQuery

In this post, find jQuery code to get Client's IP address. There are 2 free online services which allows you to get Client IP address.

1. jsonip.com
: is a free utility service that returns a client's IP address in a JSON object with support for JSONP, CORS, and direct requests. It serves millions of requests each day for websites, servers, mobile devices and more from all around the world.

All you need to do is to make a call to jsonip.com.
$(document).ready(function () {
    $.get('http://jsonip.com', function (res) {
        $('p').html('IP Address is: ' + res.ip);
    });
});

2. Smart-IP.net
: Smart IP for today is one of the leading services providing to it's users all the required information about IP-addresses and everything related to them.
$(document).ready(function () {
    $.getJSON('http://smart-ip.net/geoip-json?callback=?', function(data) {
        $('p').html('My IP Address is: ' + data.host);
    });
});
Along with the IP address, this service also provide Geo location details as well like Country, latitude, longitude etc. Following are the properties which are returned as JSON response by this service.
data.host;
data.countryName;
data.countryCode;
data.city;
data.region;
data.latitude;
data.longitude;
data.timezone;
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, May 30, 2013

Scroll Page Automatically by few pixels after every few seconds using jQuery

It would be nice feature for web pages if the web page scrolls automatically by few pixels after every 2, 3 or 5 seconds so that the users don't have to scroll it. This is quite useful for webpages having articles, posts, very long text or lengthy pages.

So, In this post you will find jQuery way to "Scroll Page Automatically by few pixels after every few seconds".

Related Post:

For the demo purpose, we will be scrolling the webpage by 200 pixels and after every 2 seconds. To do this, we need to use JavaScript "setInterval" method, which is responsible for calling a function/particular code after x seconds. So in this case, it would be 2 seconds.

Then, all you want is to get window scrollTop value and add 200 to it and then just scroll it.. Simple and Easy!!!!!
$(document).ready(function () {
    setInterval(function () {
        var iScroll = $(window).scrollTop();
        iScroll = iScroll + 200;
        $('html, body').animate({
            scrollTop: iScroll
        }, 1000);
    }, 2000);
});
Now, there is an issue which above approach. That is, once you reach at the bottom of the page you setInterval will keep on calling the function after every 2 seconds which is not desired. One way is to disable the automatic scrolling once user reaches at bottom of the page.

To do this, check if user has reached to bottom of the page and then call "clearInterval()" to stop setInterval.
$(document).ready(function () {
    var myInterval = false;
     myInterval = setInterval(function () {
        var iScroll = $(window).scrollTop();
        if (iScroll + $(window).height() == $(document).height()) {
            clearInterval(myInterval);
        } else {
            iScroll = iScroll + 200;
            $('html, body').animate({
                scrollTop: iScroll
            }, 1000);
        }
    }, 2000);
});
If the above solution don't work, then please make sure that you have include document type at top of the page.
<!DOCTYPE HTML>
The issue with above approach is that it gets executed only once. As once user reaches at bottom of the page, then setInterval is stopped. What if you want to have it again once user reaches at top of the page? Below jQuery code block exactly does the same thing.

As once bottom of the page is reached, then setInterval is stopped. So need to find a way to enable it again. And that can be done in $(window).scroll event. In this event, check if user has reached at top of the page. If yes, then reset setInterval.. That's it..

Note: For demo, I have set 500 as pixels to scroll.
$(document).ready(function () {
    var myInterval = false;
    myInterval = setInterval(AutoScroll, 2000);

    function AutoScroll() {
        var iScroll = $(window).scrollTop();
        iScroll = iScroll + 500;
        $('html, body').animate({
            scrollTop: iScroll
        }, 1000);
    }
    
    $(window).scroll(function () {
        var iScroll = $(window).scrollTop();
        if (iScroll == 0) {
            myInterval = setInterval(AutoScroll, 2000);
        }
        if (iScroll + $(window).height() == $(document).height()) {
            clearInterval(myInterval);
        }
    });
});
If the above solution don't work, then please make sure that you have include document type at top of the page.
<!DOCTYPE HTML>
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, May 28, 2013

jQuery : Execute/Run multiple Ajax request simultaneously

Yesterday for one of my requirement, I needed to execute/run multiple ajax request simultaneously or in parallel. Instead of waiting for first ajax request to complete and then issue the second request is time consuming. The better approach to speed up things would be to execute multiple ajax request simultaneously.


Related Post:

To do this, we can use jQuery .when(). The $.when() provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.

To show how it works, will send multiple ajax request to Flickr API to fetch some photos. The first request will fetch photos which are tagged with "moon" and the second request will fetch photos tagged with "bird". And then we display the results in a div of both the requests.

The basic syntax is,
$.when(request1, request2, request3.....)
So here is 2 ajax request to flickr API. To iterate through the response, there is a callback function attached to it. This callback function gets executed once both the ajax request are finished.

In the case where multiple Deferred objects are passed to $.when(), it takes the response returned by both calls, and constructs a new promise object. The res1 and res2 arguments of the callback are arrays, where res1 has response of first request and res2 has response from second request.
$(document).ready(function () {
   $.when($.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
        tags: "moon",
        tagmode: "any",
        format: "json"
   }),
   $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
        tags: "bird",
        tagmode: "any",
        format: "json"
   })).then(function (res1, res2) {
       $.each(res1[0].items, function (i, item) {
          var img = $("<img/>");
          img.attr('width', '200px');
          img.attr('height', '150px');
          img.attr("src", item.media.m).appendTo("#dvImages");
          if (i == 3) return false;
      })
      $.each(res2[0].items, function (i, item) {
          var img = $("<img/>");
          img.attr('width', '200px');
          img.attr('height', '150px');
          img.attr("src", item.media.m).appendTo("#dvImages");
          if (i == 3) return false;
      })
  });
});
See Complete Code
You can also declare what to do in case of success and failure of ajax request. Below jQuery code execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error.
$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
  .then(myFunc, myFailure);
Read more about $.when.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, May 2, 2013

Remove related videos from YouTube videos using jQuery

You must have notice that YouTube shows related videos link at the end of playback. This is sometimes quite annoying when you have embedded a video specific to your website and other related videos come up. So in this post, find jQuery code to remove related video shown at the end of playback.


Related Post:

To remove related video, all you need to do is to append "rel=0" to YouTube video URL.
$(document).ready(function () {
    $('iframe[src*="youtube.com"]').each(function () {
        var sVideoURL = $(this).attr('src');
        if (sVideoURL.indexOf('rel=0') == -1) {
            $(this).attr('src', sVideoURL + '?rel=0');
        }
    });
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, April 29, 2013

Show only Month and Year in only one jQuery UI DatePicker in case of Multiple DatePicker

In one of my previous post, I had posted about Show only Month and Year in jQuery UI DatePicker, but there was an issue with the code explained in that particular post. The issue was that it was applicable for all the datepickers present on the page and it is quite possible to have such behavior for one datepicker and rest of the datepickers control should work their default functionality.


Related Post:

How to do it?


To implement this, follow below steps only for that control for which you want to show Month and Year appear as Dropdown.
  • Set changeMonth and changeYear to true.
  • Set date format to "MM yy".
  • jQuery DatePicker has "onClose" event, which is called when Datepicker gets closed. So using this event, fetch the selected Month and Year and setDate of Datepicker.
  • jQuery DatePicker also has "beforeShow" event, which is called before the datepicker is displayed. So this event will be used to Show the previously selected Month and Year as selected. If you don't use this event, then datepicker will always show the current month and current year, irrespective of your previous selection.
  • Now, here is tricky part. Use focus() and blur() event of the textbox control to hide default behavior of the datepicker. And in focus() event, set the position of "ui-datepicker-div" which is created by datepicker control itself and this holds UI for having month and year dropdown.
$(document).ready(function () {
   $('#txtDate').datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: 'MM yy',

    onClose: function () {
      var iMonth = $("#ui-datepicker-div .ui-datepicker-month :selected").val();

      var iYear = $("#ui-datepicker-div .ui-datepicker-year :selected").val();

      $(this).datepicker('setDate', new Date(iYear, iMonth, 1));
      $(this).datepicker('refresh');
    },

    beforeShow: function () {
      if ((selDate = $(this).val()).length > 0) 
      {
        iYear = selDate.substring(selDate.length - 4, selDate.length);

        iMonth = jQuery.inArray(selDate.substring(0, selDate.length - 5), $(this).datepicker('option', 'monthNames'));

        $(this).datepicker('option', 'defaultDate', new Date(iYear, iMonth, 1));
        $(this).datepicker('setDate', new Date(iYear, iMonth, 1));
      }
    }
  });

   $("#txtDate").focus(function () {
      $(".ui-datepicker-calendar").hide();
      $("#ui-datepicker-div").position({
          my: "center top",
          at: "center bottom",
          of: $(this)
      });
   });

   $("#txtDate").blur(function () {
     $(".ui-datepicker-calendar").hide();
   });
});
See result below
See Complete Code
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...