Check/Uncheck All Checkbox by Jquery

Just copy this function.

function InitCheckAll(checkAllSelector, checkboxSelector) {
    $(checkAllSelector).change(function() {
        var e = this;
       
        $(checkboxSelector).each(function() {
            this.checked = e.checked;
        });
    });

    $(checkboxSelector).change(function() {
        if (this.checked == true) {
            var isCheckAll = true;
            $(checkboxSelector).each(function() {
                if(!this.checked) {
                    return isCheckAll = false;
                }
            });
            $(checkAllSelector)[0].checked = isCheckAll;
        } else {
            if ($(checkAllSelector)[0].checked == true) {
                $(checkAllSelector)[0].checked = false;
            }
        }
    });
}
Then you can declare select/deselect all checkbox just a line code. Notice that the paramaters should be selector string. For example:
InitCheckAll('#yourMasterCheckBoxID', '.yourChildCheckBoxClass')

Posted in , | Leave a comment

Replace multi string in Javascript

There is only way is replacing the string by regular expression. For example:

s = s.replace(/yourPaternString/g, 'yourNewValue');
However, the patern string may not work when it contains metacharacter of regex, such as . $ ^ { [ ( | ) * + ? \. We need to escape these characters by following code:
patern = patern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
text = text.replace(new RegExp(patern, 'g'), 'yourNewValue');

Leave a comment

Split string in SQL Server

Just run this function.
Notice that empty value between delimiter will return NULL, you can customize this by modify the line "insert into @tParts values( null )"

CREATE FUNCTION [dbo].[SplitString]
(
    @sString nvarchar(MAX),
    @cDelimiter nchar(1)
)
RETURNS @tParts TABLE ( part nvarchar(MAX) )
AS
BEGIN
    if @sString is null return
    declare @iStart int,
      @iPos int
    if substring( @sString, 1, 1 ) = @cDelimiter 
    begin
     set @iStart = 2
     insert into @tParts
     values( null )
    end
    else 
     set @iStart = 1
    while 1=1
    begin
     set @iPos = CHARINDEX(@cDelimiter, @sString, @iStart )
     if @iPos = 0
      set @iPos = len( @sString )+1
     if @iPos - @iStart > 0   
      insert into @tParts
      values ( substring( @sString, @iStart, @iPos-@iStart ))
     else
      insert into @tParts
      values( null )
     set @iStart = @iPos+1
     if @iStart > len( @sString ) 
      break
    end
    RETURN

END

Leave a comment

ASP MVC unobtrusive validation for dynamic html

When I add the dynamic content to page with javascript or ajax, the validation doesn't work with new content at all. I solved the problem by 2 ways.

Solution 1: Parse only changed content
$("#yourID").html(yourContent); // add html to your tag
$.validator.unobtrusive.parse($("#yourID")); // this will parse validation for new content
Solution 2: Parse validation for form tag
$.removeData($('#YourFormID').get(0), 'validator'); // clear the validation of the form tag
jQuery.validator.unobtrusive.parse('#YourFormID');

Posted in | Leave a comment

Escape jquery selector value

Declare the escape function for jquery at first

$.escape = function(str) {
  return str.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~]/g, '\\$&');
};
Example code
// the value contain special character
var searchValue = 'your-value*'; 

// this is safe with escape
var list1 = $('[value="' + $.escape(searchValue) + '"]';

// this may error without escape
var list2 = $('[value="' + searchValue + '"]'; 
Try to type the input

This is escaped value

Posted in | Leave a comment

Escape regex string javascript

Declare the escape function at first

RegExp.escape = function(string) {
  return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
};
And you can search special character like this code
var patern = '^^';
var regex = new RegExp(RegExp.escape(patern));
var text = 'Hello^^';
var match = text.match(regex));
Try to type the input

Try to type the patern with special character

Matched text found:

Posted in | Leave a comment

Javacript get local date time

JS just support to get UTC time. There is how to get local time.

function GetLocalTime() {
    var date = new Date();            
    var n = date.getTime() - (date.getTimezoneOffset() * 60000);            
    return new Date(n);
}    


Leave a comment

Jquery $(document).ready vs $(window).load

document.ready will execute after all HTML of the page is loaded.

window.load will wait for all elements are loaded, include image, iframe. window.load can be used in body onload.

$(document).ready will trigger before $(window).load. Use window.load when you want retrieve attribute of image, iframe on page start.

Leave a comment

Difference between String and string C#

The 'string' keyword is equivalent of 'System.String' so you don't need to using namespace System like following code.

//using System;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string s1 = string.Empty;
            System.String s2 = System.String.Empty;
            String s3 = String.Empty; // compile error namespace could not be found
        }
    }
}

Posted in | Leave a comment

Change default error message "The value ... is not valid for..."

This is my solution. Tested on MVC 3 and MVC 4.

  1. Create App_GlobalResources folder in project (easy way is right click to project -> Add -> Add ASP.NET folder -> App_GlobalResource).
  2. Add a resx file to App_GlobalResources (e.g. YourResource.resx).
  3. Add resource key "PropertyValueInvalid". By default, the message is "The value {0} is not valid for {1}". You can change or translate whatever you want.
  4. Add the code DefaultModelBinder.ResourceClassKey = "YourResource" to Application_Start function in Global.asax.

Posted in | Leave a comment

Show spinner on load image.

Click on links to see spinner on load image.

Show image 1
Show image 2
Show image 3
function changeImg(url) {
    var img = document.getElementById('previewImg');
    var spinner = document.getElementById('spinner');
    // show spinner
    spinner.style.display = '';
    img.style.display = 'none';
    img.onload = function() {
        spinner.style.display = 'none';
        this.style.display = '';
        this.onload = null;
    }
    img.src = url;
}  

Posted in | Leave a comment

Resize image and keep aspect ratio.

Width:
Height:

Javascript

function Resize(img) { var w = document.getElementById('t1').value; var h = document.getElementById('t2').value; var d = document.getElementById('d1'); d.style.width = w + 'px'; d.style.height = h + 'px'; img.style.width = 'auto'; img.style.height = 'auto'; if(img.width / img.height >= w / h) { img.style.width = d.style.width; } else { img.style.height = d.style.height; } }

Posted in | Leave a comment

Search

Swedish Greys - a WordPress theme from Nordic Themepark. Converted by LiteThemes.com.