Skip to content Skip to sidebar Skip to footer

Highlight The Specific Select2 Passing The Id Selector To The Function

I need to highlight only the #vans and not the #cars Sometimes #vans can be multiple and sometimes it can be a non multiple too. However I must be able to specifically pass the ID

Solution 1:

If you know that only the select#vans needs highlighting, you don't need to iterate over all Select2 jQuery items. Additionally, your highlightSelect2 isn't using the selector you've passed in.

Using your code sample, I've modified it so that only the #vans element will be highlighted by:

  • not iterating over all select2 elements (using .each)
    • This lets you only highlight the #vans, directly
  • Modifying highlightSelect2 to use the passed-in selector
  • Removing isMultiple logic — it wasn't necessary

<!DOCTYPE html><html><body><scriptsrc="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script><linkrel="stylesheet"href="https://fonts.googleapis.com/icon?family=Material+Icons"><linkhref="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css"rel="stylesheet" /><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script><selectname="cars"class="mySelect"id="cars"multiple><optionvalue="volvo">Cars</option></select><selectname="vans"class="mySelect"id="vans"><optionvalue="volvo">Vans</option></select><script>functionhighlightSelect2(selector) {

    $(selector)
      .next('.select2-container')
      .find(".select2-selection")
      .effect("highlight", {
        color: '#f88'
      }, 10000);
  }

$(document).ready(function() {
  //initilize select2
  $('.mySelect').select2( { width: "25%" });

  // highlight the #vans select2highlightSelect2("#vans");
});
</script></body>

Run the code snippet and you'll see it works as you expect for your specific example.

Post a Comment for "Highlight The Specific Select2 Passing The Id Selector To The Function"