Combining Multiple attributes in jQuery

Below are some of the code snippets available in jQuery for you to combine your multiple lines of code:

Combining multiple css properties or element attributes:

Statement: Set the width and height attributes for a table with id=mytable

Statement: Set the css properties of width, height, background-color for a div with id=mydiv

Combining element multiple selector:

Statement: Set the width, height and background-color css properties for controls with id=mydiv1, mydiv2 and mydiv3

$(“#mydiv1, #mydiv2, #mydiv3”).css({width:’50px’,height:’40px’,background-color:’#F2F2F2′});

Combining attribute selectors:

Statement: Find out those elements with an id attribute, having ‘name’ ending with ‘mydiv’ and the ‘checked’ state being ‘checked’


Combining attribute selectors with psuedo properties:

Statement: Delete dropdown option values myvalue3, myvalue4 from a dropdown with id=mydiv

$(“#mydiv options:not([value=’myvalue1′][value=’myvalue2′]).remove();
$(“#mydiv options:[value=’myvalue3′],[value=’myvalue4′]”).remove();

Note: The coma separator in the last statement above will perform a repeat operation on the same element which implies that the above statement is a combined version of the below statements:

$(“#mydiv options:[value=’myvalue3′]”).remove();

$(“#mydiv options:[value=’myvalue4′]”).remove();
Setting multiple attributes for an element:

Statement: Create a new anchor tag and set its id, class and redirect url

$(‘</a>’, {
id : ‘myId’,
class : ‘myClass’,
href : ‘mytest.html’

Combining Objects in jQuery:

Statement: To combine or merge two objects in jQuery

var parentObject = { property1: false, property2: 5, property3: “foo” };
var options = { property1: true, property3: “bar” };

jQuery.extend(parentObject, options);
//Final values for parentObject { property1: true, property2: 5, property3: “bar” }

Happy Coding!!!

SharePoint Client Object Model (ECMAScript) #2 – Update Web Properties

SharePoint Client Object Model (ECMAScript) provides the capabilities of SharePoint Server Object capabilities at the client side. In this tutorial, let me show you how you can play around with the Client Object Model through IE Developer Toolbar how to update Web properties.

Check the screenshot below, to know what we are trying to achieve here:

Below is the function that i have used:

    function updateTitle() {
        var ctx = new SP.ClientContext.get_current();
        this.web = ctx.get_web();
        ctx.executeQueryAsync(Function.createDelegate(this, this.onUpdate),
            Function.createDelegate(this, this.onFail));
    function onUpdate(sender, args) {
        alert(‘title updated’);
    function onFail(sender, args) {
        alert(‘failed to update title. Error:’+args.get_message());
ExecuteOrDelayUntilScriptLoaded(updateTitle, “sp.js”); 

The above ECMAScript access the SharePoint’s client context object and updates the Title property of it. It is essential to note that “SP.js” is loaded before this script execution occurs. This is the reason for using the “ExecuteOrDelayUntilScriptLoaded” function.

SharePoint Client Object Model (ECMAScript) #1 – Get Context Object

SharePoint Client Object Model (ECMAScript) provides the capabilities of SharePoint Server Object capabilities at the client side. In this tutorial, let me show you how you can play around with the Client Object Model through IE Developer Toolbar.

Check the screenshot below, to know what we are trying to achieve here:

Below is the function that i have used:

function getWebProperties() {
var ctx = new SP.ClientContext.get_current();
this.web = ctx.get_web();
ctx.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
Function.createDelegate(this, this.onFail));
function onSuccess(sender, args) {
alert(‘web title:’ + this.web.get_title() + ‘\n ID:’ + this.web.get_id() +
‘\n Created Date:’ + this.web.get_created());
function onFail(sender, args) {
alert(‘failed to get list. Error:’+args.get_message());

ExecuteOrDelayUntilScriptLoaded(getWebProperties, “sp.js”);

The above ECMAScript access the SharePoint’s client context object. It is essential to note that “SP.js” is loaded before this script execution occurs. This is the reason for using the “ExecuteOrDelayUntilScriptLoaded” function.

Best Practices for jQuery Developers

Following are some of the best practices that you could follow while working with jQuery:

  • Plugins:
    • Please avoid unnecessary use of plugins
    • If a plugin is being used, respect the authors work and ensure that the plugin file is reused with the license comments intact
    • If you are writing a reusable functionality in the code, always move it into a jQuery plugin format, to be reused across the site
  • Coding:
    • Use jQuery CDN (google or Microsoft or jQuery) as much as possible for script registration, if its fine with clients. To be on the safer side, you could have a fallback code as well:
      <!– Grab Google CDN jQuery. fall back to local if necessary –> 

<script src=”“></script> 

<script>!window.jQuery && document.write(‘<script src=”js/jquery-1.4.2.min.js”><\/script>’)</script>

  • Avoid unnecessary upgrades of jQuery, unless there are features, which you require or some plugins require. Stick to one version from the beginning. (ex. 1.5.1)
  • Avoid writing event handler attributes (onclick etc.), instead use live or bind methods to attach the respective event handlers.
  • Avoid mixing javascript code with jQuery code.
  • Cache any jQuery selector, if reused in multiple statements.
    Ex. Avoid $(“#x”).val(); $(“#x”).attr(“align”,”right”); Use var $x = $(“#x”); $x.val();$x.attr(“align”,”right”);
  • Ensure that you place ready function in your code. $(document).ready(function(){});
  • Use find method, instead of building a complex jQuery selector.

//Fine in modern browsers, though Sizzle does begin “running”

$(‘#someDiv p.someClass’).hide(); 

// Better for all browsers, and Sizzle never inits. 


  • Avoid misusing $(this).
    Ex. Use instead of $(this).attr(‘id’)
  • Keep your code safe, by using noConflict() method or by passing jQuery.
    Ex. (function($){})(jQuery); or by wrapping it in a ready method.
  • Avoid declaring new jQuery selectors within foreach, instead declare them outside and reuse it inside the loop.
  • Use $.ajax instead of $.get or $.getJSON, because internally they call $.ajax.
  • Use JSON formats for communications.
  • Ensure that you move your jQuery codes to a separate javascript file, instead of inline scripts.
  • Compress javascript files for better performance.
  • Combine multiple css() calls or attr() calls into one. In case of attributes, you could also pass them as shown below: 
$(‘</a>’, {

    id : ‘myId’, 

    className : ‘myClass’, 

    href : ‘mytest.html’ 


  • Debugging:
    • Use Developer Toolbars and Inspectors to debug your code from client side. You do not need to perform deployments and builds to debug your jQuery code(s).
  • jQuery Cheat Sheet:
    • Always keep a jQuery cheat sheet handy with you to know about the list of functions available for you. Download here

Below are some more useful links you could check out:

Some words of caution:

  • $.ajax has issues in making cross domain AJAX calls. As a solution, you can get a patched version of $.ajax from the net.
  • Avoid http request on https sites. Your user will be prompted with a nagging security popup, which on rejection can break your request.
  • Avoid loading multiple jQuery versions.
  • Majority of the jQuery plugins are browser compatible, but NOT ALL. Read the plugin documentations carefully and use them judiciously.

This might appear to be a drop from the ocean. But it will guide them in the right direction.

WebRequest.GetResponse() throwing SSL secure channel error

Problem Statement:

WebRequest.GetResponse() is one of the most common ways we adopt to perform a HTTPWebRequest from our server side. This case was a specific one, although the error appeared to be more generic in nature. In fact it happened only in SharePoint and not in my .Net application.

The error observed in the GetResponse() method was:

“The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel”

One of the root cause of this problem is due to the certificate issue. And to be more precise the certificate validation has failed.


The solution to this problem, more or less i would call it a decent workaround is to use the ServerCertificateCallbackValidation method from the HttpWebRequest class and forcefully return true.

Create a static method for validating the certificate

private static bool ValidateFbCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors)
return true;

Just before u make your HttpWebRequest try using this.

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(ValidateFbCertificate);

HttpWebRequest …..;

This should skip any certificate errors.

Happy Coding!!!

Convert a JSON string into a C# object

There could be scenarios in our project wherein we consume a service which returns back a JSON message. These JSON message is infact a stringified version of an object and are recognized as a simple string format by our server side. Decoding them gets difficult at the first shot.

But C# itself has got a solution for this. And that is the JavaScriptSerializer object from the namespace System.Web.Script.Serialization;

Let me take you through the conversion of a JSON string to a custom C# object here. Its pretty simple!!

#1: ADD the following namespace to your code

Using System.Web.Script.Serialization;

#2: INITIALIZE the JavaScriptSerializer object

JavaScriptSerializer jss= new JavaScriptSerializer();

#3: IMPLEMENT the Deserialize method of JavaScriptSerializer, passing two important information – one is the custom object (MyCustomObject) and the JSON string (jsonResponse)

MyCustomObject user = jss.Deserialize<MyCustomObject>(jsonResponse);

#4: DEFINE the MyCustomObject class in your code. Ensure that the object structure matches the JSON string format.

public class MyCustomObject


public string myProperty1;

public string myProperty2;


You can then use the Deserialized object “user” and get its properties like:
user.Property1 or user.Property2.

For information on the Serialization of C# object to JSON, you can refer my previous post:

Generate JSON String Output in C#


Happy Coding!!!