Easy way to quick select a whole optgroup in select box

前端 未结 4 982
星月不相逢
星月不相逢 2021-01-02 20:32

I have a select box in which i can select multiple options. In the select box are multiple optgroups. Is there an easy way to select a whole optgroup at once in javascript?

4条回答
  •  有刺的猬
    2021-01-02 20:52

    I suggest using jQuery (or another framework) to quickly handle DOM selections. Give each optgroup a class to make it easier to grab it.

    $("optgroup.className").children().attr('selected','selected');
    

    If you want to select the entire group based on the user selecting the group, do the following:

    $("optgroup.className").select(function(e) {
      $(this).children().attr('selected','selected');
    });
    

    **Both examples are untested pseudo-code, but they should work with minimal changes, if necessary.

    If you cannot use a framework, you'll have to traverse the DOM yourself to find the optgroup and children. You could attach a listener to the select element to grab the element being selected then traverse to the children that way, too.

提交回复
热议问题