【问题标题】:jquery-select2 obtaining ID and text from a select box?jquery-select2 从选择框中获取 ID 和文本?
【发布时间】:2014-11-10 18:37:46
【问题描述】:

我正在使用 jquery-select2 插件,并且我有以下由 AJAX 自动填充的字段:

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

这里是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"));

结果函数中的 console.log 中显示的数据结构如下:[{"id":"someone@gmail.com", "text":"someone"}]

选择选项后,尝试 console.log($("#player2").select2("val")) 给我 ID,但我似乎无法获得文本。在这种情况下,以下任何一项都无法获取“某人”的文本值,我看不出哪里出错了。

$("#player2 option:selected").text()
$("#player2 option:selected").select2().text()
$("#player2").text()

【问题讨论】:

    标签: javascript jquery jquery-select2 jquery-select2-3


    【解决方案1】:
      $("#player2").select2('data')[0].id;
      $("#player2").select2('data')[0].value;
    

    【讨论】:

      【解决方案2】:
      $("#player2").select2('data').text
      

      使用版本 3.5.1

      【讨论】:

        【解决方案3】:
        // this will give you value of selected element.
        $("#player2").val(); 
        

        【讨论】:

          【解决方案4】:

          我使用了表单标签并使用提交事件捕获了值的 id。

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

          【讨论】:

            【解决方案5】:
            .on("select2:select", function(e) {
                console.log(e.params.data.id);
            });
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2012-10-05
              • 1970-01-01
              • 1970-01-01
              • 2011-04-12
              • 1970-01-01
              • 2013-07-04
              相关资源
              最近更新 更多