Advertisement
sdevilcry

Custom dropdown with form / input management

Jul 10th, 2013
565
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function DropDown(el) {
  2.     this.dd = el;
  3.     this.placeholder = this.dd.children('span');
  4.     this.opts = this.dd.find('ul.dropdown > li');
  5.     this.val = '';
  6.     this.index = -1;
  7.     this.initEvents();
  8.  
  9.     // Prepare Form / input selection
  10.     var $input = $('input[name="' + this.dd.children('ul').attr('data-target') + '"]');
  11.     var $form = this.dd.parents('form');
  12.  
  13.     // Check if the form exist
  14.     if ($form.length) {
  15.         if (!$input.length) {
  16.             $input = $('<input type="hidden" name="' + this.dd.children('ul').attr('data-target') + '" value="" />');
  17.             $input.appendTo($form);
  18.         }
  19.     }
  20.  
  21.     this.input = $input;
  22. }
  23.  
  24. DropDown.prototype = {
  25.     initEvents : function() {
  26.         var obj = this;
  27.  
  28.         obj.dd.on('click', function(event){
  29.             $(this).toggleClass('active');
  30.             return false;
  31.         });
  32.  
  33.         obj.opts.on('click',function(e){
  34.             var opt = $(this);
  35.             obj.val = opt.text();
  36.             obj.index = opt.index();
  37.             obj.placeholder.text(obj.val);
  38.  
  39.  
  40.             if (obj.input) {
  41.                 obj.input.attr('value', $(this).attr('data-id'));
  42.             }
  43.         });
  44.     },
  45.     getValue : function() {
  46.         return this.val;
  47.     },
  48.     getIndex : function() {
  49.         return this.index;
  50.     }
  51. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement