polu polu - 1 year ago 49
Javascript Question

How to add border to Select2 element with jQuery?

I'm trying add border to Select2 with jQuery, but it's not working.


$('#search').click(function () {
if ($('#select :selected').text() == ""){


border: 2px solid red !important;


<select style="width:300px" id="felevselect">
<option disabled="disabled" selected="selected"></option>
<select style="width:120px" id="napselect">
<option disabled="disabled" selected="selected"></option>
<option value="1">Hétfő</option>
<option value="2">Kedd</option>
<option value="3">Szerda</option>
<select style="width:90px" id="select">
<option disabled="disabled" selected="selected"></option>
<button id="search" type="button" class="btn btn-default">Keres</button>

How to add border to only one Select2 element?

Answer Source

If I got you correctly, here is working code:


<select style="width: 100px;" id="my-select">
    <option value="1">Item1</option>
    <option value="2"></option>
    <option value="3">Item2</option>
<button>Click me!</button>


.alert {
    border: 2px solid red !important;


$('button').on('click', function() {        
     if ($('#my-select :selected').text() == ""){

     // using following code you can toggle alert class
     // $('.select2').toggleClass("alert", $('#my-select :selected').text() == "");

Also provided Codepen

As you know, when using select2, this plugin hide the select element and show you some generated HTML (instead of select), you can check the generated html using browser's console


If the #select is your target, you can change the code to following, then your mentioned issue (in comment section) will be fixed: