• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 53
  • Last Modified:

jquery,. sorting

How to sort asc  - selectBondName below?


    $(xml).find(xmlnode).each(function () {
                if (bondState == $(this).find('GeneralInformation').find('State').text()) {
                    selectBondName = $(this).find('GeneralInformation').find('Name').text();
                    selecthtml += '<option value="' + selectBondName + '">' + selectBondName + "(" + bondState + ") "  + '</option>';
                    i = i + 1;
                  //  alert(selecthtml);
                }
    });

Open in new window

0
ITsolutionWizard
Asked:
ITsolutionWizard
  • 4
  • 4
  • 2
1 Solution
 
HainKurtSr. System AnalystCommented:
what is xmlnode?
can you put those in a jsfiddle.net?
0
 
ITsolutionWizardAuthor Commented:
no
0
 
HainKurtSr. System AnalystCommented:
good luck then :)
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
Julian HansenCommented:
Please disregard the previous comment - it is not representative of how we prefer to deal with queries on Experts Exchange. Most experts on these forums are here because we want to help, not to chase points.

I took a look at your earlier questions and obtained some XML from those questions. I have put together a sample that shows how to extract options from an XML document (I used a more generic version of your data), put them into an array, sort the array and add the sorted data as options to a drop down. You did not supply us with information on where bondState comes from or where the options go to so I filled in those gaps with my own code.

The sample below therefore demonstrates a solution but you may need to tweak it to fit your requirements.
The XML looks like this
<?xml version="1.0" encoding="utf-8"?>
<Container>
  <GeneralInformation UI="BondInfo">
    <State>CA</State>
    <Name>Zebra</Name>
  </GeneralInformation>
  <GeneralInformation UI="BondInfo">
    <State>CA</State>
    <Name>Aardvark</Name>
  </GeneralInformation>
  <GeneralInformation UI="BondInfo">
    <State>CA</State>
    <Name>Marmoset</Name>
  </GeneralInformation>
</Container>

Open in new window

The HTML looks like this (basically just the <select>). I gave it an ID of bondList for the purposes of the demo so I could target it to add the options
	<select id="bondList"></select>

Open in new window

The JavaScript looks like this
<script>
$(function() {
  // Hard coded for demo
  var bondState = 'CA';

  // Included for demo
  var bondList = $('#bondList');

  $.get('t2775.xml', function(xml) {

    // Array to store our otpions in
    var options = [];
    
    // Extract bond Name data from XML and add to options array
    $(xml).find('GeneralInformation').each(function (i,e) {
      if (bondState == $(e).find('State').text()) {
        options.push($(e).find('Name').text());
      }
    })
    
    // Sort array and iterate over the array
    options.sort();
    for(var i = 0; i < options.length; i++) {
      var selectBondName = options[i];
      var option = $('<option/>', {value: selectBondName}).html(selectBondName + "(" + bondState + ") ");
      bondList.append(option);
    }
    });
});
</script>

Open in new window


And you can see it working here
0
 
ITsolutionWizardAuthor Commented:
Maybe it is better you take a look of my codes below. They are all working.  Except I want selectedBondName to be sorted.

function fnGetBondNameList(bondState) {
            $.ajax({
                url: "http://localhost:5489/BondList.xml",
                success: function (xml) {
                    parseSelectXML(xml,"bondName","Bond",bondState);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert("Status: " + xhr.status);
                    alert("Error: " + thrownError);
                }
            });
    }
function parseSelectXML(xml, selectid, xmlnode, bondState) {
    var selecthtml = "", selectBondName="";
    var i = 0;
    $(xml).find(xmlnode).each(function () {
                var options = [];
                if (bondState == $(this).find('GeneralInformation').find('State').text()) {
                    selectBondName = $(this).find('GeneralInformation').find('Name').text();
                    selecthtml += '<option value="' + selectBondName + '">' + selectBondName + "(" + bondState + ") "  + '</option>';
                    i = i + 1;
                  //  alert(selecthtml);
                }
    });
             $("#" + selectid).prop("disabled", false);
             //$('#' + selectid).html(selecthtml).val(selectBondName);

             $('#' + selectid).html(selecthtml);
             $('#' + selectid + ' option:first').attr('selected', 'selected');


             //modal information
             $('#' + "bondListFilterByState").html(selecthtml).val(selectBondName);
             $('#' + "bondlistFilterByState_selectedBondName").html(selectBondName).vaL;
             $('#' + "bondlistFilterByState_selectedState").html(bondState).val;
             //modal end information
         } 

Open in new window

0
 
Julian HansenCommented:
Here is my code adapted to match your layout
<script>
$(function() {
  // Hard coded for demo
  var bondState = 'CA';

  // Included for demo
  $.get('http://localhost:5489/BondList.xml')
	.done(function(xml) {
		parseSelectXML(xml,"bondName","Bond",bondState);
	})
	.fail(function( jqXHR, textStatus, errorThrown) {
		alert("Status: " + xhr.status);
		alert("Error: " + thrownError);	
	})
});

function parseSelectXML(xml, selectid, xmlnode, bondState) {
    // Array to store our otpions in
    var options = [];
    
    // Extract bond Name data from XML and add to options array
    $(xml).find('GeneralInformation').each(function (i,e) {
      if (bondState == $(e).find('State').text()) {
        options.push($(e).find('Name').text());
      }
    })
    
    // Sort array and iterate over the array
    options.sort();

    // Save a reference to the <select> rather than fetching it each time
    var bondList = $('#' + selectid);

    for(var i = 0; i < options.length; i++) {
      var selectBondName = options[i];
      var option = $('<option/>', {value: selectBondName}).html(selectBondName + "(" + bondState + ") ");
      bondList.append(option);
    }
	
	// This code does not make any sense - what are you trying to do here?
/*
	$('#' + "bondListFilterByState").html(selecthtml).val(selectBondName);
    $('#' + "bondlistFilterByState_selectedBondName").html(selectBondName).vaL;
    $('#' + "bondlistFilterByState_selectedState").html(bondState).val;	
*/
}
</script>

Open in new window

I have commented out the last 3 lines of the parseSelectXML function because I don't know what it is you are trying to do there - the code does not make sense to me.

I have not used your method for adding options to the select because in the context of the question asked it is not the right way to do it - the method I have used is better.

I have also used $.get instead of $.ajax - they do the same thing $.ajax is usually for when we need control over more of the options for the asynch call.
0
 
ITsolutionWizardAuthor Commented:
I prefer to use same coding style. Is it possible to not use get ...
0
 
Julian HansenCommented:
Is it possible to not use get ...
I did use get - refer line 7.
0
 
ITsolutionWizardAuthor Commented:
Julian: thank you for your helps. However, it returns duplicated records. Anyway, you are good and I should give you points as well.
0
 
Julian HansenCommented:
@ITSolutionWizard - thank you but if the solution is not right we must fix it.

In my sample above http://www.marcorpsa.com/ee/t2775.html you can see that it works based on the data provided.

If in your case it is producing duplicates - please provide the data that is resulting in duplicates so we can fix.

Off the top of my head you can probably do this by modifying your parseSelectXML to look look like this

function parseSelectXML(xml, selectid, xmlnode, bondState) {
    // Array to store our otpions in
    var options = [];
    
    // Extract bond Name data from XML and add to options array
    $(xml).find('GeneralInformation').each(function (i,e) {
      if (bondState == $(e).find('State').text()) {
        var name = $(e).find('Name').text();

        // CHECK IF ALREADY IN options ARRAY
        if (options.indexOf(name) == -1) {
          options.push(name);
        }
      }
    })
    
    // Sort array and iterate over the array
    options.sort();
    var bondList = $('#' + selectid);

    for(var i = 0; i < options.length; i++) {
      var selectBondName = options[i];
      var option = $('<option/>', {value: selectBondName}).html(selectBondName + "(" + bondState + ") ");
      bondList.append(option);
    }
}

Open in new window


Updated sample here
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

  • 4
  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now