[英]how to get text from multiple selected values of select2 input using javascript
I used select2 for my input select and set multiple is true. 我使用select2作为输入选择,并将倍数设置为true。 In my case, I tried to get text array from multiple selected values using javascript function. 就我而言,我尝试使用javascript函数从多个选定值中获取文本数组。
This is my javascript and html input : 这是我的javascript和html输入:
<script type="text/javascript">
function getRoles(val) {
$('#role-cm_role_text').val('');
var data = $('#role-cm_role').select2('data')[0].text;
$('#role-cm_role_text').val(data);
$('#role-cm_role').on('select2:unselecting', function (e) {
$('#role-cm_role_text').val('');
});
}
</script>
<select id="role-cm_role" class="form-control" name="Role[CM_ROLE][]" multiple size="4" onchange="getRoles(this.value)" style="display:none">
<option value="INQUIRY">CM Inquiry</option>
<option value="SUPERVISOR">CM Supervisor</option>
<input type="hidden" id="role-cm_role_text" class="form-control" name="Role[CM_ROLE_TEXT]">
So if I try to select one value, the result of CM_ROLE_TEXT
is same with CM_ROLE
. 所以,如果我尝试选择一个值,结果CM_ROLE_TEXT
一样的是CM_ROLE
。 But if I try to select multiple values, the resul of CM_ROLE_TEXT
is just get a first value of CM_ROLE
. 但是,如果我尝试选择多个值,的resul CM_ROLE_TEXT
刚刚拿到的第一个值CM_ROLE
。
Result if try to select multiple values : 如果尝试选择多个值,则结果:
[CM_ROLE] => Array
(
[0] => INQUIRY
[1] => SUPERVISOR
)
[CM_ROLE_TEXT] => CM Inquiry // I need the result of CM_ROLE_TEXT is same with the result of CM_ROLE
Anyone can help me how to fix my issue? 任何人都可以帮助我解决问题吗? Thank you 谢谢
From what i can see, the problem is with this line right here 从我所看到的,问题出在这条线
var data = $('#role-cm_role').select2('data')[0].text;
As you are only selected the 1st [0]
of the array only. 由于仅选择了阵列的第一个[0]
。 So this is indeed the expected behaviour. 因此,这确实是预期的行为。 So to get all the results text in the array, you can perhaps do something like this 因此,要获取数组中所有结果文本,您可能可以执行以下操作
var data = $('#role-cm_role').select2('data').map(function(elem){
return elem.text
});
then you will have an array of all the strings selected. 那么您将拥有所有选定字符串的数组。 Read about map
function here : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map 在此处阅读有关map
功能的信息: https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Here is a live example : https://jsbin.com/qujocujuko/edit?html,js,output 这是一个实时示例: https : //jsbin.com/qujocujuko/edit?html,js,output
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.