3

I'm in trouble here... I am having this strange output from a dynamic form I'm building at the moment.

Basically I have a JavaScript completing a form while the user selects an option, starting with 'Soil type' » 'Slope angle' » 'Water Speed'. Now, 'Water Speed' has decimal values, and they all add up to the dropdown selection fine, but completely out of order.

My selection list is looking like:

1, 2, 3, 1.5, 2.5

Instead of:

1, 1.5, 2, 2.5, 3

I tried converting all of them to float values with no luck...What's bugging me, is that the Object and it's propreties are declared in the correct order and console.log() outputs them fine as well, so I am curious to see if this is simply HTML fault and if there's any workaround.

By the way, the way I add them to the select tag is:

for(speed in obj[speeds]){
$('<option value=\"'+speed+'\">'+speed+'</option>').appendTo('select[name=waterspeed]');
        }

Thanks in advance!

2
  • 1
    can you show the definition of speeds, and how you are trying to sort them? Commented Jan 2, 2012 at 16:49
  • Oh well...right after I submitted the question, I tried wrapping the object propreties with a double quote like "1.0", "1.5", ... and it seems to be working properly on the select dropdown. Anyway, I didn't close the question since there could be a better answer without using a cast to string after specifiying that all items are float values. Can't seem to find anywhere how the select works in this sort of cases... Commented Jan 2, 2012 at 16:50

1 Answer 1

1

Try sorting your speeds array first:

obj[speeds].sort(function(a, b) {
    return a - b
});

Also, for in loops are not usually recommended for arrays. Consider using a "regular" for loop:

for(var i = 0, max = obj[speeds].length; i < max; i++) {
   var speed = obj[speeds][i];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.