如何设置值而不是select2中的文本

时间:2016-09-15 05:57:18

标签: javascript jquery select2

$('select').select2({width:"300"});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<select id="convertIt" multiple>
    <option value="A">Australia</option>
    <option value="U">US </option>
    <option value="J">Japan</option>
    <option value="E">Europe</option>
    <option value="C">Canada</option>
  </select>

我也试过了id但没有用过

$('#convertIt').select2({
    placeholder: "Select an country"
}).select2("data",
     [{"id":"test1","text":"Henry Ford"},{"id":"test2","text":"Tom Phillips"}]
);

由于

2 个答案:

答案 0 :(得分:1)

试试这个:

function formatSelection(val) {
  return val.id;
}

$('#convertIt').select2({
    placeholder: "Select an country",
    formatSelection: formatSelection,
}).select2("data",
     [{"id":"test1","text":"Henry Ford"},{"id":"test2","text":"Tom Phillips"}]
);

答案 1 :(得分:1)

&#13;
&#13;
function formatSelection(val) {return val.id;}

$('select').select2({templateSelection: formatSelection,width:"300"});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<select id="convertIt" multiple>
    <option value="A">Australia</option>
    <option value="U">US </option>
    <option value="J">Japan</option>
    <option value="E">Europe</option>
    <option value="C">Canada</option>
  </select>
&#13;
&#13;
&#13;