4

I have a dropdown, and in another process add optgroups/options to that dropdown, and that part works fine.

But I may need to add similar optgroups, with more data, and I want to check for the existence of that optgroup, and if it exists, don't add it, but just add options to the existing optgroup.

I have been searching around, and can't seem to find any help on selecting an optgroup.

My existing dropdown has the id of "user_search_select" and possible optgroup values could be like "dept_name" or "loc_name" or "last_name"

So after I add more data, I then may want to sort the options inside each optgroup, is that possible and how so?

Thank You!

crosenblum
  • 1,869
  • 5
  • 34
  • 57

1 Answers1

6

Check this out. Although I haven't try it it's look like that it could do the job about the sorting.

About the checking of existance. Basically you can check with:

<script type="text/javascript">
    $(document).ready(function() {
        if($('#mySelect optgroup[label=New group]').html() == null){
           $('#mySelect').append('<optgroup label="New group"></optgroup>');
           $('#mySelect optgroup[label=New group]').append('<option value="1">New element</option>');
        } else {
           $('#mySelect optgroup[label=New group]').append('<option value="1">New element</option>');
        }
    });
</script>

In the script the if check if there is optgroup with label New group, if there is no such group - add the new group and then add the option in that group. The else part, just add the option in the existing New group.

Then you should apply the sort with the plugin.

Nik Chankov
  • 6,049
  • 1
  • 20
  • 30
  • 2
    The best way to test for an element's existence is to use the `length` property. `if($('#whatever').length) { /* it exists */ } else { /* does not exist */ }` – Matchu Jul 21 '10 at 20:05
  • Yep correct! I had problems while I tested that solution (a typo) and I tried with html() and then I forgot to change :) – Nik Chankov Jul 21 '10 at 20:09
  • Can I easily remove the children of a named optgroup? – crosenblum Jul 22 '10 at 21:50
  • Yes of course: $('#mySelect optgroup[label=New group]').children().remove(); Btw, if that answer is working for you, please consider to accept it :) – Nik Chankov Jul 22 '10 at 22:31