简体   繁体   English

jquery-select2从选择框中获取ID和文本?

[英]jquery-select2 obtaining ID and text from a select box?

I'm using the jquery-select2 plugin, and I have the following field that is being autopopulated by AJAX: 我正在使用jquery-select2插件,我有以下由AJAX自动填充的字段:

<input type="hidden" id="player2" class="form-control select2">

Here is the javascript: 这是javascript:

$('#player2').select2({
    placeholder: "Select an opponent",
    allowClear: false,
    ajax: {
        dataType: "json",
        url: "getUsers.php",
        data: function (term) {
            return {
                q: term, // search term
            };
        },
        results: function (data) {
            console.log(data);
            return {results: data};
        },

    }
}); 
console.log($("#player2").select2("val"));

The data, as shwon in the console.log within the results function, is structured like this: [{"id":"someone@gmail.com", "text":"someone"}] 数据,如结果函数中的console.log中的shwon,结构如下:[{“id”:“someone@gmail.com”,“text”:“someone”}]

After the choice is selected, trying to console.log($("#player2").select2("val")) gives me the ID, but I can't seem to get the text. 选择选项后,尝试console.log($(“#player2”)。select2(“val”))给我ID,但我似乎无法得到文本。 None of the following works to get the text value of "someone" in this case and I don't see where I'm going wrong. 在这种情况下,以下所有方法都无法获得“某人”的文本值,而且我看不出我出错的地方。

$("#player2 option:selected").text()
$("#player2 option:selected").select2().text()
$("#player2").text()
  $("#player2").select2('data')[0].id;
  $("#player2").select2('data')[0].value;
$("#player2").select2('data').text

使用3.5.1版

// this will give you value of selected element.
$("#player2").val(); 

I have used form tag and using submit event I have captured id of value. 我使用了表单标签并使用提交事件我已经捕获了id的值。

$("#Selector").submit(function (event) {
  console.log($("#Selector").serialize())
});
//other option is below 
$("#select_machine").select2('data')[0].text
.on("select2:select", function(e) {
    console.log(e.params.data.id);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM