Adorablepolak Adorablepolak - 9 days ago 4
Javascript Question

Select2 Issue copying option selected to a disabled field

I am trying to copy the selected value from a select2 component to another one which is disabled. I was able to transfer the value from both hidden selects (select2 actually hides the regular selects and creates a new html structure) but I am not able to copy the text to the span.
I have a jsfiddle that exemplifies my problem: http://jsfiddle.net/vktyaLmp/.

Is this the right approach to copying values from a select2 component to another one?
Is there a built-in method?

This is my code:

$("#originSelect, #targetSelect").select2({
allowClear: true,
minimumInputLength: 1
});

if ($('#originSelect').val() != 0) {
$('#select2-chosen-2').text( $('#originSelect').val() );
}

Answer

Select2 gives you built in function to get/set values directly. You can replace your javascript with the following code :

$("#originSelect, #targetSelect").select2({
    allowClear: true,
    minimumInputLength: 1
});

$("#originSelect").change(function(e) {
    if ($('#originSelect').val() != 0) {
        $('#targetSelect').select2('val', $('#originSelect').select2('val'));
    }
});

(I just tested it in your Fiddle)

Comments