My plugin doesn't work with multiple selectors

Maybe it's something simple but I have a problem.

I created a plugin, but it only works well with a single selector, if I put several, that's where the problem comes from.

Although I use $(this) to select the current select, it ends up selecting all and replaces the value in all the selects where it finds them. I leave my jsfiddle for review.

Look at the select # 1 and # 3.

$(document).ready(function() {
  $("#sel1, #sel2, #sel3").SelectPopup();
});

See my jsfiddle

Upvotes: 0

Views: 38

Answers (1)

charlietfl
charlietfl

Reputation: 171679

I'm not going to rewrite your plugin for you but will show you the basics of isloating the element instances within your plugin.

this inside the plugin function is a jQuery object that includes all of the matching elements from the selectors.

You want an internal each to loop over and isolate each of those element instances.

Following is a very crude plugin that just wraps each of the selects in a parent container and adds a change event listener to each instance. It is not very practical by itself but should give you the foundation to rebuild the one you are working on

$.fn.mySelect = function(options) {
  // `this` is jQuery object that contains all elements in collection
  // we return it so the plugin can be chained to other jQuery methods if needed
  // also use `each` to isolate individual elements in the collection
  return this.each(function() {
    // `this` is instance of element in collection
    var $currentSelect = $(this);
    // wrap each element and add a change event listener
    $currentSelect.wrap('<div class="select-wrapper">')
      .change(function() {
        console.log('Select id "' + this.id + '" changed')
      });
  });
}

$("#sel1, #sel2, #sel3").mySelect()
.select-wrapper {
  display: inline-block;
  border: 1px solid #ccc;
  margin-right: 20px;
  padding: 1em
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sel1">
  <option value="1">A1</option>
  <option value="2">A2</option>
  <option value="3">A3</option>
</select>

<select id="sel2">
  <option value="10">B1</option>
  <option value="20">B2</option>
  <option value="30">B3</option>
</select>

<select id="sel3">
  <option value="1">C1</option>
  <option value="2">C2</option>
  <option value="3">C3</option>
</select>

Upvotes: 2

Related Questions