Putra
Putra

Reputation: 79

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. In my case, I tried to get text array from multiple selected values using javascript function.

This is my javascript and html input :

<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. But if I try to select multiple values, the resul of CM_ROLE_TEXT is just get a first value of 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

Upvotes: 1

Views: 6767

Answers (1)

Abhishek Gupta
Abhishek Gupta

Reputation: 1337

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

Here is a live example : https://jsbin.com/qujocujuko/edit?html,js,output

Upvotes: 5

Related Questions