polu polu - 2 months ago 13
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.

JavaScript:

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


CSS:

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


HTML:

<select style="width:300px" id="felevselect">
<option disabled="disabled" selected="selected"></option>
</select>
<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>
<select style="width:90px" id="select">
<option disabled="disabled" selected="selected"></option>
<option>8:00</option>
<option>9:00</option>
<option>10:00</option>
<option>11:00</option>
</select>
<button id="search" type="button" class="btn btn-default">Keres</button>


How to add border to only one Select2 element?

Answer

If I got you correctly, here is working code:

HTML

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

CSS

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

JS

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

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

Update

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

$('#select').next().addClass("alert");
Comments