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 select2elements (using.each)- This lets you only highlight the #vans, directly
 
- This lets you only highlight the 
- Modifying highlightSelect2to use the passed-inselector
- Removing isMultiplelogic — it wasn't necessary
<!DOCTYPE html>
<html>
<body>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
  <select name="cars" class="mySelect" id="cars" multiple>
    <option value="volvo">Cars</option>
  </select>
  <select name="vans" class="mySelect" id="vans">
    <option value="volvo">Vans</option>
  </select>
  
  
  <script>
  function highlightSelect2(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 select2
  highlightSelect2("#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"