views:

98

answers:

1

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!

+1  A: 

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
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
Yep correct! I had problems while I tested that solution (a typo) and I tried with html() and then I forgot to change :)
Nik
Can I easily remove the children of a named optgroup?
crosenblum
Yes of course: $('#mySelect optgroup[label=New group]').children().remove();Btw, if that answer is working for you, please consider to accept it :)
Nik
Thank you very much!
crosenblum