How to use "tags" with Select2

d00rman

I have this "Select2" dropdownmenu which get populated from ajax and php. The script I have here is allowing one choice to be made, and passed into a html element. I'd like to use this code with "tags". I've tried but can't figure out how to fetch all selected values? How do I send what is selected?

HTML

//form
<input type='hidden' class='col-md-4' id='choose_usr_email' name='choose_usr_email' required>
//Snap up whats chosed
<input type='text' id='chosen_usr_email' name='chosen_usr_email'>

Javascript

$(document).ready(function(){
var chosenUsr = $('#choose_usr_email');
$("#choose_usr_email").select2({
    tags: true,
    placeholder: "Välj användare..",
    ajax: {
    url: "time.php",
    dataType: 'json',
        //search term
        data: function (term, page) {
            return {
            q: term, // search term
            page: page
            };
        },
        results: function (data, page) {
        return { results: data};
        }
    } // Ajax Call
}); // Select2

// Start Change
$(chosenUsr).change(function() {
    var usrId = $(chosenUsr).select2('data').id;
    var usrEmail = $(chosenUsr).select2('data').text;
    var timeNr = $(chosenUsr).select2('data').timenr;
    var usrfName = $(chosenUsr).select2('data').usrfname;
 
    $('#chosen_usr_id').val(usrId);
    $('#chosen_usr_email').val(usrEmail);
    $('#chosen_usr_time_nr').val(timeNr);
    $('#chosen_usr_fname').val(usrfName);
  
  }); //Change
}); //Document Ready
Artur Filipiak

With select2 v.4.0 you can use multiple dropdown.

Set name as choose_usr_email[], so that it will create array of tags on submit.

HTML

<form action="" id="tagForm">
    <select multiple="true" name="choose_usr_email[]" id="choose_usr_email" class="form-control select2">
        <!-- if tags are loaded over AJAX, no need for <option> elments -->
    </select>
    <!-- more form elements ... -->
    <button type="submit">Submit</button>
</form>

Script

$('#choose_usr_email').select2({
    tags: true,
    // automatically creates tag when user hit space or comma:
    tokenSeparators: [",", " "],
    ajax: {
        url: "time.php",
        dataType: 'json',
        //search term
        data: function (term, page) {
            return {
                q: term, // search term
                page: page
            };
        },
        results: function (data, page) {
            return { results: data};
        }
    }
});

// handle form submission:
$('#tagForm').submit(function(e){
    e.preventDefault();
    $.ajax({
        // PHP file where you send selected values:
        url      : "file.php",
        // if you want to use $_POST in PHP, uncomment the line below:
        // type  : 'POST',
        dataType : 'json',
        // serialize the form:
        data     : $('#tagForm').serialize(),
        success  : function(response){
            // handle server response ...
        }
    });
});

PHP (file where you send selected values)

<?php

    // If 'type' is not specified in AJAX, use $_GET
    // check if 'choose_usr_email' exists in AJAX request
    if(isset($_GET['choose_usr_email']){
        // if exists, loop through the values:
        foreach($_GET['choose_usr_email'] as $key => $value){
            // do something with each $value (each submitted tag)
        }
    }

?>

DEMO


For Select2 < v.4.0

$('#choose_usr_email').val(); returns each selected tag id (if specified) or text, separated by coma (1,2,3,...).

$('#tagForm').submit(function(e){
    e.preventDefault();
    $.ajax({
        // PHP file where you send selected values:
        url      : "file.php",
        // if you want to use $_POST in PHP, uncomment the line below:
        // type  : 'POST',
        dataType : 'json',
        // request data, split input field value by comma:
        data     : {
            choose_usr_email : $('#choose_usr_email').val().split(',')
        },
        success  : function(response){
            // handle server response ...
        }
    });
});

Then you can process the AJAX request the same way as in previous PHP example.

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Creating new tags in a Select2 tag textarea

来自分类Dev

How to pass <option> attributes to select2?

来自分类Dev

AngularJS + Select2 (Multiple - Tags) - 有时会显示其他标签

来自分类Dev

Select2与textarea

来自分类Dev

CkEditor use <b> tags instead <strong>

来自分类Dev

How to replace font tags with span?

来自分类Dev

Select2()不是函数

来自分类Dev

Select2程序访问

来自分类Dev

替换select2选项?

来自分类Dev

Select2搜索选项

来自分类Dev

Select2加载问题

来自分类Dev

select2 不是函数

来自分类Dev

未应用 Select2

来自分类Dev

克隆 select2 选项

来自分类Dev

How to use SELECT inside COUNT in MYSQL

来自分类Dev

How to select custom layout to use in Apache POI

来自分类Dev

在select2中搜索select属性

来自分类Dev

到达 select2 的数据属性 select

来自分类Dev

Use HtmlAgilityPack to determine if string contains ONLY tags from list of allowed tags

来自分类Dev

YII2 : kartik Select2

来自分类Dev

Use str_replace or other function to replace tags

来自分类Dev

How can I archive old git tags?

来自分类Dev

How to get list of latest tags in remote git?

来自分类Dev

iOS Instagram Tags Text Layout? How Is It Done?

来自分类Dev

How to get audio tags using audio fingerprint

来自分类Dev

Javascript : how to insert tags around a text selection?

来自分类Dev

how to use kill SIGUSR2 in bash?

来自分类Dev

How to use dual monitors on a system with 2 computers?

来自分类Dev

Selenium IDE select2 selecting an item