Pankaj Mishra
Pankaj Mishra

Reputation: 20348

how to get some filtered data from xml with the help of jquery?

 <Item id="419" rank="0.0000" date_added="2012-09-24T19:43:14" date_end="2012-10-15T19:43:14" uid="134333" price="  ,-" district="-1" district_text="Friend" cid="9" cid_text="Underholdning" img_height_thumb="433" />
  <Item id="418" rank="0.0000" date_added="2012-09-24T19:17:42" date_end="2012-10-15T19:17:42" uid="134332" price="  ,-" district="-1" district_text="Friend" cid="9" cid_text="Underholdning" img_height_thumb="254" />
  <Item id="405" rank="102.0000" date_added="2012-09-23T18:55:20" date_end="2012-10-14T18:55:20" uid="134331" price="  102,-" district="-1" district_text="Friend" cid="761" cid_text="Mote" img_height_thumb="280" />

This is sample xml data. And I am using this code to get xml.

I want to filter all data rank which is greater then 0. And I want to add filter only in this palce so my rest code won't change. So how could i filter items variable and get filter values in other variable. so the loop don't get effected. I can change the name of variables in for loop.

Please suggest me any idea for this.

xmlDoc = xmlhttp.responseXML;
        var items1 = xmlDoc.getElementsByTagName("Item");

    var items = $(items1).filter('Item').each(function () {
        var bRank = $(this).attr('rank');
        var tempRank = bRank.replace("0000", "").replace(".", "");
        if (tempRank > 0)
            return this;
    });

alert(items.length);
        alert(items1.length);

Answer of both alert is 3.

but answer should like this for first alert 1 and for second alert 3.

but i am getting same response each alert. please check and let me know your suggestion. Thanks

Upvotes: 0

Views: 110

Answers (1)

raina77ow
raina77ow

Reputation: 106375

You probably wanted to use jQuery's .filter method with function argument instead:

var items = $(items1).filter(function () {
    var bRank = $(this).attr('rank');
    return parseInt(bRank, 10) > 0;
});

Here's JS Fiddle to play with. I obviously have to build the XML string by myself, and I got rid of replace code, as parseInt is much more suitable for, well, parsing an integer part from a string.

.each just invokes some code for each element of some collection, but it doesn't collect the results (as .map and .filter do) - in fact, it just returns the original collection. The only useful thing about return statement in .each function is that it can be used to break from an iteration (when falsy value is returned).

Upvotes: 1

Related Questions