Javascript 如何在 Select2 中使用“标签”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28744574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:20:19  来源:igfitidea点击:

How to use "tags" with Select2

javascriptjqueryhtml

提问by d00rman

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

我有这个“Select2”下拉菜单,它是从 ajax 和 php 填充的。我在这里的脚本允许做出一个选择,并传递到一个 html 元素中。现在我喜欢将此代码与“标签”一起使用。我试过了,但不知道如何获取所有选定的值?我如何发送所选内容?

HTML

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

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

回答by Artur Filipiak

With select2 v.4.0you can use multipledropdown.

使用select2 v.4.0,您可以使用多个下拉列表。

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

将 name 设置为choose_usr_email[],以便在提交时创建标签数组。

HTML

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 (发送所选值的文件)

<?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

对于 Select2 < v.4.0

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

$('#choose_usr_email').val();返回每个选定的标签id(如果指定)或text,以昏迷(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.

然后,您可以按照与前面的 PHP 示例相同的方式处理 AJAX 请求。