February 20, 2010

Iterating over JSON object (string ) with jquery

We had a scenario where in we need to search for particular object in collection. Whenever the user changes something in dropdown in ASP.NET we need to show some value in a label. If we take the drop down value to server it would take time.... so what we thot is we searialized the object using JavascriptSerializer in ASP.NET and converted to JSON string.. passsed to a javascript function to search.... (whenever dropdown changes)... I was literally amazed with the power of JSON and jquery combination... thot i would share with people in need.....

Here is the JSON string...in Javascript...

var obj = [{"Description":"No jquery pricing group may be used for Testing", "ID":1, "TempID":1, "CompareID":3}, {"Description":"No jquery pricing group may be used for Testing", "ID":2, "TempID":2, "CompareID":3}, {"Description":"No jquery pricing group may be used for Testing", "ID":3, "TempID":3, "CompareID":3}, {"Description":"No jquery pricing group may be used for Testing", "ID":4, "TempID":4, "CompareID":3}, {"Description":"No jquery pricing group may be used for Testing", "ID":5, "TempID":1, "CompareID":4}, {"Description":"Jquery required for pricing Testing", "ID":6, "TempID":2, "CompareID":4}, {"Description":"Jquery required for pricing Testing", "ID":7, "TempID":3, "CompareID":4}, {"Description":"Jquery required for pricing Testing", "ID":8, "TempID":4, "CompareID":4}, {"Description":"No jquery pricing group may be used for Testing", "ID":9, "TempID":1, "CompareID":5}, {"Description":"Jquery required for pricing Testing", "ID":10, "TempID":2, "CompareID":5}, {"Description":"Jquery required for pricing Testing", "ID":11, "TempID":3, "CompareID":5}, {"Description":"Jquery required for pricing Testing", "ID":12, "TempID":4, "CompareID":5}];

We had a requirement to searhch the description for matching TempID and COmpareID...

Our Javascript function was amazingly...

function Myfunc(ID1,Exp1){jQuery.each(obj, function Test(x) { if (obj[x].TempID == ID1 && obj[x].CompareID == Exp1) //return obj[x].Description; alert(obj[x].Description);}); }

This would have helped you to understand the power of jqeury

No comments: