View difference between Paste ID: BAdcNaUQ and xBGNQuR6
SHOW: | | - or go back to the newest paste.
1
$.fn.odropdown = function(options) {
2
3
	var default_settings = {
4
		placeholder : 'span',
5
		placeholder_text : '',
6-
		selected_index : 0
6+
		selected_index : -1
7
	};
8
9
	var settings = $.extend( {}, default_settings, options );
10
	var selector = $(this).selector;
11
12
	return this.each(function() {
13
		var $this = $(this);
14
		var $list = $this.find('ul');
15
		var selected_index = settings.selected_index;
16
		var $placeholder = $this.find(settings.placeholder);
17
18
		if (settings.placeholder_text.length) {
19
			$placeholder.text(settings.placeholder_text);
20
		}
21
22
		if (settings.selected_index >= 0 && $this.find('li').length >= settings.selected_index) {
23
			var $li = $this.find('li:eq(' + settings.selected_index + ')');
24
			selectElementOfList($li);
25
		} else {
26
			$this.attr('tabindex', -1);
27
		}
28
29
		// Prepare Form / input selection
30
		var $input = $('input[name="' + $list.attr('data-target') + '"]');
31
		var $form = $this.parents('form');
32
33
		// Check if the form exist
34-
			$(this).toggleClass('active');
34+
35
			if (!$input.length) {
36
				$input = $('<input type="hidden" name="' + $list.attr('data-target') + '" value="" />');
37
				$input.appendTo($form);
38-
		$list.find('li').on('click',function(e){
38+
39-
			var $li = $(this);
39+
40
41
		$this.on('click', function(event){
42
			var is_active = $this.hasClass('active');
43
44
			// Delete all active class during to stay focus on the last one
45
			if ($(selector + '.active').length > 0) {
46
				$(selector + '.active').removeClass('active');
47
			}
48
49
			if (!is_active) {
50
				$this.addClass('active');
51-
				// Turn back off list
51+
52-
				$this.toggleClass('active');
52+
			event.preventDefault();
53
			return false;
54
		});
55
56
		$list.find('li').on('click',function(e) {
57
			selectElementOfList($(this));
58
			$this.removeClass('active');
59
60
			// Have to be called and return false, else parent click will be triggered
61
			e.preventDefault();
62
			return false;
63
		});
64
65
		function selectElementOfList($li) {
66
			selected_index = $li.index();
67
			$placeholder.text($li.text());
68
			$this.attr('tabindex', selected_index);
69
70
			if ($input) {
71
				$input.attr('value', $li.attr('data-id'));
72
73
				// Trigger some events
74
				$input.trigger('change');
75
				$input.trigger('click');
76
			}
77
		}
78
	});
79
};