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

LVL 1
ITsolutionWizardAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook 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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.