moses toh
moses toh

Reputation: 13172

How to change background color select 2 using javascript?

Demo and my code is like this : http://jsfiddle.net/fc1qevem/10/

My javascript code is like this :

var select02 = $('#select02');

$(select02).select2({
    data: [{
        id: 0,
        text: "test01"
    }, {
        id: 1,
        text: "test02"
    }, {
        id: 2,
        text: "test03"
    }, {
        id: 3,
        text: "test04"
    }, {
        id: 4,
        text: "test05"
    }],
     placeholder: "Branch name",
});

I want change the background color of select2 to blue color

I want change the background color using javascript

Whether it can be done?

Thank you

Upvotes: 3

Views: 10210

Answers (5)

M. Radinmehr
M. Radinmehr

Reputation: 118

I use it this way and it works very well:

$("#select02").siblings('.select2').children('.selection').children('.select2-selection').css('background-color', 'blue')

Upvotes: 2

Migu Wala Ngalan
Migu Wala Ngalan

Reputation: 1

// Css code
.bg_color {
     background-color: blue !important;
}

// Javascript code
// just put this code under the load function

$(select02).select2({ containerCssClass: "bg_color " });

This is how select2 adding class to the container or default css ".select2-container--default .select2-selection--single" of select2 where you can edit the background color of the container. Hope it helps you.

Upvotes: 0

Webdev
Webdev

Reputation: 647

Try the code below:-

document.getElementById("select02").style.backgroundColor="blue";

Upvotes: -1

Vladu Ionut
Vladu Ionut

Reputation: 8193

add this in your css

.select2-selection{
  background-color:blue !important;
}

js solution

 $(select02).select2({
    data: [{
        id: 0,
        text: "test01"
    }, {
        id: 1,
        text: "test02"
    }, {
        id: 2,
        text: "test03"
    }, {
        id: 3,
        text: "test04"
    }, {
        id: 4,
        text: "test05"
    }],
     placeholder: "Branch name",
}).data("select2").$container.find(".select2-selection").css('background-color', 'blue');

Upvotes: 2

df_development
df_development

Reputation: 1

When you will change the background-color using JavaScript try this:

$('.select2-selection').css('background-color', 'blue');

Upvotes: 0

Related Questions