简体   繁体   中英

How can I use this multiselect dropdown twice on one page so each instance outputs to its own array?

I want to place two separate multiselct dropdown menus on one page for a form I am designing.

I found this lovely dropdown with checkboxes that I would like to use:

https://codepen.io/bseth99/pen/fboKH

I am trying to figure out the best way to run two instances of this dropdown on the same page, so that each dropdown's selections are saved in their own array.

var options = [];

$( '.dropdown-menu a' ).on( 'click', function( event ) {

   var $target = $( event.currentTarget ),
       val = $target.attr( 'data-value' ),
       $inp = $target.find( 'input' ),
       idx;

   if ( ( idx = options.indexOf( val ) ) > -1 ) {
      options.splice( idx, 1 );
      setTimeout( function() { $inp.prop( 'checked', false ) }, 0);
   } else {
      options.push( val );
      setTimeout( function() { $inp.prop( 'checked', true ) }, 0);
   }

   $( event.target ).blur();

   console.log( options );
   return false;
});

Right now, if I place two instances of the button's HTML on my page, both dropdowns will modify the same "options" array because it's using a class selector for dropdown-menu. I know I can use an ID selector instead of a class selector, and then just use the same block of jQuery over again with a different array, but is that really the best way to do this? I am new to jQuery but that seems bloated.

$( '.dropdown-menu a' ).on( 'click', function( event ) {

   var $target = $( this ),
       val = $target.data( 'value' ),
       $inp = $target.find( 'input' ),
       idx;

   var options = $target.closest('.dropdown-menu').data('options') || [];


   if ( ( idx = options.indexOf( val ) ) > -1 ) {
      options.splice( idx, 1 );
      setTimeout( function() { $inp.prop( 'checked', false ) }, 0);
   } else {
      options.push( val );
      setTimeout( function() { $inp.prop( 'checked', true ) }, 0);
   }

   $target.closest('.dropdown-menu').data('options', options);

   $( event.target ).blur();

   return false;
});

console.log($( '.dropdown-menu:eq(0)' ).data('options'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM