-3

Only when I have the code in an on change event does the list become sorted. I want it to sort when the page loads. I have tried using onload but to no success.

Also I’m trying to make it so whatever the user selects, that value is the first one on the list.

Works…

myDropdown.onchange = function () {
         $("#dropdown").append($("#dropdown option").sort(function(a, b) {
                  return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
           }))
        myTextBox.value = this.value;
}

Doesn’t Work…

// var myDropdown = $('#dropdown');
// var opts_list = myDropdown.find('option');

// function sortTheList() {
//     $("#dropdown").append($("#dropdown option").sort(function(a, b) {
//         return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
//     }))
// };

// myDropdown.onload = function () {
//     $('#dropdown option').sort(function(a,b) { return $(a).text() > $(b).text() ? 1 : -1; });
//     myDropdown.html('').append('#dropdown option');
// }
// myDropdown.onload = function () {
//     $("#dropdown").on($("#dropdown option").sort(function(a, b) {
//         return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
//     }))
// }
2
  • myDropdown is a jQuery object. It doesn't have an onload, but you can do $(document).ready(function() { ... }); Commented May 16, 2016 at 19:43
  • Take a look at this stackoverflow.com/questions/33757017/… Commented May 16, 2016 at 19:45

1 Answer 1

0

Instead of onload, try using onDOMContentLoaded.

See: https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded

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.