Форум программистов, компьютерный форум, киберфорум
jQuery
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.62/13: Рейтинг темы: голосов - 13, средняя оценка - 4.62
 Аватар для Братуха
5 / 5 / 5
Регистрация: 15.07.2012
Сообщений: 773

Как достать данные из мультиселекта?

20.12.2012, 16:34. Показов 2781. Ответов 6
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Привет всем. Скачал скрипт мультиселекта, но как извлечь данные что бы потом их обработать в php. вот html
HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<form action="#" method="post" name="form" id="form">
            
      
 
            
                <label class="examples">jQuery MultiSelect allows works with multiple instances</label>
                <select id="basicmultiselect" name="basicmultiselect" class="arc90_multiselect" multiple="multiple" title="Colours">
                    <option value="#ff0">red</option>
                    <option value="#0f0">green</option>
                    <option value="#ff0" selected="selected">orange</option>
                    <option value="#00f">blue</option>
                    <option value="#f0f">purple</option>
                </select>
</div>
           
        
        </form>
а вот jqueri
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
var multiSelect_timer = null;  /* handle mouseouts. */
var select_state      = false; /* false = closed, true = open */
var is_clicked        = false; /* false = checkbox has not been clicked
                                  true  = checkbox has been clicked
                               */
 
 
/*@function multiSelect
  @description Creates a multiselect box w/checkboxes allowing a
                       user to select multiple items. We also provide a
                       dynamically updating title field, that displays the
                       current total of selected items (or none).
  @param options An array of possible configuration values.
*/
jQuery.fn.multiSelect = function(options)
{
    /* Sets the default options, if non are provided.  */
    if(!options) options = {};
    
    /* Title text displayed when no items are selected. */
    var no_selection   = options.no_selection  || "Нет выбраных категорий";
    
    /* Title text displayed when one or more items are selected. */
    var selected_text  = options.selected_text || " Категорий выбрано";
    
        /* Minimun number of items a selectbox must have in order to display
       the 'select all' option.
    */
    var select_all_min = typeof(options.select_all_min) != 'undefined'
                       ? options.select_all_min : 6;    
    
    return this.each(function()
    {
        /* Timeout passed to setTimeout( ). */
        var timeout = 0;
    
        /*@function multiSelect_closeWindow
          @description Closes the multiSelect by clicking the title
          and unbinding the click( ) to the body.
        */
        function multiSelect_closeWindow( )
        {
            selectTitle.click( );
            $('body').unbind("click", multiSelect_closeWindow);
        }
                        
        /* Workflow:
            1. Set up the HTML elements that will display the multiSelect.
            2. Bind the events that will display the HTML elements.
            3. Hide the original select box.
        */
        var hiddenSet = new Array( );
 
        var id    = $(this).attr('id');
        var title = $(this).attr('title');
        var name  = $(this).attr('name');
 
        /* Code taken from the original multiSelect. */
        var fieldWidth = this.className.toLowerCase().indexOf('fieldwidth-');
        var valueWidth = this.className.toLowerCase().indexOf('valuewidth-');
        
        if (fieldWidth >= 0)
        {
            var q = this.className.slice(fieldWidth);
            fieldWidth = (q.slice(0, q.indexOf(' ') < 0? q.length: q.indexOf(' '))).slice('fieldwidth-'.length);
            fieldWidth = parseFloat(fieldWidth) == fieldWidth? fieldWidth+'px': fieldWidth;
        }
        else fieldWidth = '';
        
        if (valueWidth >= 0)
        {
            var q = this.className.slice(valueWidth);
            valueWidth = (q.slice(0, q.indexOf(' ') < 0? q.length: q.indexOf(' '))).slice('valuewidth-'.length);
            valueWidth = parseFloat(valueWidth) == valueWidth? valueWidth+'px': valueWidth;
        }
        else valueWidth = '';        
 
        /*** STEP 1: Set up the HTML elements that will display the multiSelect */
 
        /* Create our container elements */
        var selectDiv   = $('<div id="multiSelect-' + id + '" class="multiSelect">');
        var selectTitle = $('<div id="multiSelect-' + id
                        + '-title" class="title" title="' + title
                        + '">').text(no_selection);
        
        selectTitle.css('width', fieldWidth);
        selectDiv.css('width', valueWidth);
        
        var selectContent = $('<div id="multiSelect-' + id
                          + '-content" class="multiSelectContent collapsed">');
        var selectList    = $('<ul>');
 
        /* Set up their heirarchy (selectDiv contains selectTitle, selectContent contains selectList) */
        selectDiv.append(selectTitle);
        selectContent.append(selectList);
        
        /* When the user clicks the select box title, display the contents. */
        selectTitle.click(function()
        {
            select_state = ( select_state )? false : true;
            selectContent.toggleClass('collapsed');
        });
        
        /* if selectContent is moused out, only close the list if
           the user clicks the body.
        */
        jQuery([selectDiv.get(0), selectContent.get(0), selectList.get(0)]).mouseout(function()
        {
            multiSelect_timer = setTimeout(function()
            {
                if(multiSelect_timer != null)
                {
                    clearTimeout(multiSelect_timer);
                    multiSelect_timer = null;
                    if ( select_state == true )
                    {
                        $('body').bind("click", multiSelect_closeWindow);
                    }
                }
            }, timeout); 
        });
 
 
        /* Clear the timeout if selectContent is moused over. This removes the
           bind on the body click, allowing the user to click on the list
           without it closing.
        */
        jQuery([selectDiv.get(0), selectContent.get(0), selectList.get(0)]).mouseover(function()
        {
            $('body').unbind("click", multiSelect_closeWindow);
            if ( multiSelect_timer == null ) return;
            clearTimeout(multiSelect_timer);
            multiSelect_timer = null;
        });
 
        /* If the select all option is configured, display it. */
        if(jQuery('option',this).length >= select_all_min)
        {
            var li = jQuery('<li class="a9selectall">').appendTo(selectList);
            var checkbox = jQuery('<input type="checkbox" id="multiSelect-options-selectAll-' +id+ '" name="multiSelect-options-selectAll-' +id+'" value="1" title="Select All" />').appendTo(li);
            var label = jQuery('<label for="multiSelect-options-selectAll">Выбрать все категории</label>').appendTo(li);
            
            /* Set the cursor. */
            setHandCursor(checkbox, label);
            
            /* Called when a user clicks on the 'Select All' checkbox. */       
            checkbox.click(function()
            {
                toggleAllLabelsAndCheckboxes(this.checked, selectList, true);
                updateSelectTitle(selectList, selectTitle);
                is_clicked = true; /* Don't run the <li> code. */
            });
            
            /* Called when a user clicks on the 'Select All' <label>. */
            label.click(function( )
            {
                toggleAllLabelsAndCheckboxes(Boolean($('input', $(this).parent()).attr('checked')),
                                       selectList, false);
                updateSelectTitle(selectList, selectTitle);            
                is_clicked = true; /* Don't run the <li> code. */
            });
            
            /* Called when a user clicks the 'Select All' <li>. */
            li.click(function()
            {
                if ( is_clicked == false )
                {
                    toggleAllLabelsAndCheckboxes(Boolean($(':checkbox', $(this)).attr('checked')),
                                                   selectList, false);
                    updateSelectTitle(selectList, selectTitle);
                }
                is_clicked = true;
            });
        }
 
            
        /* Constructs the selectboxes. Happens everytime. */
        jQuery('option',this).each(function(i)
        {
            // Helper variables
            var value      = jQuery(this).attr('value');
            var text       = jQuery(this).text();
            var isSelected = $(this).attr('selected') == true? 'checked="yes"' : '';
            
            var fontWeight = ( isSelected != '' )? 'bold' : 'normal';
            var checkBoxID = 'multiSelect-options-' + id + '-' + i;
 
            var li = jQuery('<li>').appendTo(selectList);
                
            /* Construct the checkbox. */
            var checkbox = jQuery('<input type="checkbox" id="' + checkBoxID
                         + '" name="multiSelect-options-' + id + '[]" value="' + value
                         + '" title="' + text + '"' + isSelected + '/>').appendTo(li);
            
            var label = jQuery('<label for="' + checkBoxID
                      + '">' + checkBoxID + '</label>').text(text).css('font-weight', fontWeight).appendTo(li);           
            
            /* Set the cursor. */
            setHandCursor(checkbox, label);
            
            /* Update the title. */ 
            updateSelectTitle(selectList, selectTitle);
                    
            /* The user has selected a checkbox:
               1. Bold the selected element
               2. Update the title
            */
            checkbox.click(function()
            {
                /* Bold if checked, unbold if unchecked. */
                fontWeight = ( this.checked == 1 )? 'bold' : 'normal';
                $('label', $(this).parent( )).css('font-weight', fontWeight);
                
                /* Update the title. */
                updateSelectTitle(selectList, selectTitle);
                
                /* We do not want the <li> or <label> code to run. */
                is_clicked = true;
            });
        });
        
        /* The user selected the <label>. Record this because
           we only want the list events to happen once.
        */
        $('label', selectList).click(function( )
        {
            is_clicked = true;
        });
 
        /* When a user selects any portion of the <li>
           element toggle the checkbox and label.
        */
        $('li', selectList).click(function()
        {
            if ( is_clicked == false )
            {
                var fontWeight = 'normal'; /* Default state. */
                var isChecked  = '';       /* Default state. */
                
                if( $(':checkbox', $(this)).attr('checked') != true )
                {
                    isChecked  = 'checked';
                    fontWeight = 'bold';
                }
 
                $('label', $(this)).css('font-weight', fontWeight);
                $(':checkbox', $(this)).attr('checked', isChecked);
 
                /* Update the title. */
                updateSelectTitle(selectList, selectTitle);
            }
            is_clicked = false;
        });
 
        /* Attach the multiSelect to the DOM */
        jQuery(this).before(selectDiv);
        jQuery(this).before(selectContent);
 
        /* Remove the selectbox, identified by 'id' because we only want
           to show the div checkboxes.
        */
        $(this).remove('#' + id);
    });
 
 
    /*@function     toggleAllLabelsAndCheckboxes
      @description  Toggles the state of all the checkboxes within the
                    multiSelect, plus applies bold or normal weight to the
                    <label>s.
      @param        checked     Is the selected checkbox checked or not.
      @param        selectList  The list elements.
      @param        condition   A boolean value used for comparision.
    */
    function toggleAllLabelsAndCheckboxes(checked, selectList, condition)
    {
        var fontWeight = 'normal'; /* Default state. */
        var isChecked  = '';       /* Default state. */
 
        /* If 'select all' is checked we set font-weight to 'bold',
           otherwise set it to 'normal'.
        */
        if ( checked == condition )
        {
            isChecked  = 'checked';
            fontWeight = 'bold';
        }
 
        $('label',selectList).css({'font-weight':  fontWeight});
        $(':checkbox', selectList).attr('checked', isChecked);        
    }
    
    
    /*@function     setHandCursor
      @description  Changes the cursor from a pointer to a hand.
     
      @param        checkbox
      @param        label
    */
    function setHandCursor(checkbox, label)
    {
        checkbox.css('cursor', 'pointer');
        checkbox.css('cursor', 'hand');
        label.css('cursor',    'pointer');
        label.css('cursor',    'hand'); 
    }
    
    
    /*@function    updateSelectTitle
      @description Calculates the number of currently checked items
                               and updates the select box title to reflect that.
      @param       selectList
      @param       selectTitle
    */
    function updateSelectTitle(selectList, selectTitle)
    {
        /* Calculate the total checked items. */
    var selectCount = $('li:not(.selectall) :checkbox:checked', selectList).length+1 - (this.checked ? 1 : 1);
        
        /* Update the title: 'n selected' || 'No selection'. */
        selectTitle.text(selectCount > 0 ? (selectCount + selected_text) : no_selection);
    }
}
Заарие большое спасибо.
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
20.12.2012, 16:34
Ответы с готовыми решениями:

как достать данные из грида на C#
помогите! не могу достать данные из грида на VB.NET все логично решалось: Private Sub publicationGridWiew_DoubleClick(ByVal sender...

Как правильно достать данные?
Помогите пожалуйста достать данные, скажем например Host users:

Как достать данные из таблицы
Всем привет. подскажите как достать данные из таблицы. в таблице три поля. имя , телефон и описание. Я хочу чтоб когда я ввожу в...

6
 Аватар для nonamez123
189 / 185 / 54
Регистрация: 23.10.2010
Сообщений: 1,336
20.12.2012, 18:21
JavaScript
1
2
3
jQuery(document).ready(function(){
jQuery('#basicmultiselect ').change(function(){alert(jQuery(this).val();)});
});

Не по теме:

Не проверял

1
 Аватар для Братуха
5 / 5 / 5
Регистрация: 15.07.2012
Сообщений: 773
20.12.2012, 20:00  [ТС]
А как мне можно передать все выбранные элементы через запятую в php переменную, что бы мне потом использовать данные. Может правда вопрос не по разделу, но все же буду очень признателен, сам точно этого не сделаю. Зарание большое спасибо
0
 Аватар для Dolphin
814 / 797 / 201
Регистрация: 21.09.2012
Сообщений: 2,656
20.12.2012, 20:06
А почему бы сразу php не обрабатывать?
0
 Аватар для Братуха
5 / 5 / 5
Регистрация: 15.07.2012
Сообщений: 773
20.12.2012, 20:43  [ТС]
Каким образом?
0
 Аватар для Dolphin
814 / 797 / 201
Регистрация: 21.09.2012
Сообщений: 2,656
20.12.2012, 20:49
HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
<form method="post" name="form" id="form" ectype="multipart/form-data">
                <label class="examples">jQuery MultiSelect allows works with multiple instances</label>
                <select id="basicmultiselect" name="basicmultiselect[]" class="arc90_multiselect" multiple="multiple" title="Colours">
                    <option value="#ff0">red</option>
                    <option value="#0f0">green</option>
                    <option value="#ff0" selected="selected">orange</option>
                    <option value="#00f">blue</option>
                    <option value="#f0f">purple</option>
                </select>
</div>
           
        
</form>
А в php уже ловим эту переменную
PHP
1
2
3
4
5
6
7
8
9
<?php
if($_POST['basicmultiselect'])
    $value = $_POST['basicmultiselect'];
 
    //Если нужно значение через запятую, тогда добавляем еще вот это
    if(is_array($value)) $value = implode(',', $value);
 
}
?>
0
 Аватар для Братуха
5 / 5 / 5
Регистрация: 15.07.2012
Сообщений: 773
21.12.2012, 14:24  [ТС]
селект почему-то ничего не передает как будто его там совсем нет
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
21.12.2012, 14:24
Помогаю со студенческими работами здесь

Как достать данные из таблицы по Id
Такая ситуация: Есть две таблицы в бд. В первой записан id_человека и name человека. Во-второй, id_человека, age, height. Мне нужно из...

Как достать данные из таблицы
Здравствуйте, Столкнулся с такой проблемой. Имеется практически готовое решение, но меня попросили добавить небольшой функционал. В...

Как достать данные из класса
Добрый вечер. Имею абстрактный и несколько наследуемых от него классов. Получаю доступ только к данным абстрактного класса, а нужно...

Как достать данные из комбобокса?
Здравствуйте. Таблица 1 (Т1) id name Таблица 2 (Т2) id ...

Как достать данные из файла?
Например имеется файл test.txt, в котором есть список имэйлов. Каждый имэил с новой строчки. Как правильно достать их? Т.е. мне...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Новые блоги и статьи
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост.
Programma_Boinc 28.12.2025
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост. Налог на собак: https:/ / **********/ gallery/ V06K53e Финансовый отчет в Excel: https:/ / **********/ gallery/ bKBkQFf Пост отсюда. . .
Кто-нибудь знает, где можно бесплатно получить настольный компьютер или ноутбук? США.
Programma_Boinc 26.12.2025
Нашел на реддите интересную статью под названием Anyone know where to get a free Desktop or Laptop? Ниже её машинный перевод. После долгих разбирательств я наконец-то вернула себе. . .
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Рецензия / Мнение/ Перевод Нашел на реддите интересную статью под названием The Thinkpad X220 Tablet is the best budget school laptop period . Ниже её машинный перевод. Thinkpad X220 Tablet —. . .
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru