Search code examples
selectjquery-select2required

Select2 from select with required not change border color.


i have add in my form this css rule to add a border color orange if is required.

:required{
    border-color: #f8ac59 !important;
}

but this not work for Select2, when i try with this i add this individual:

.select2-selection{
    border-color: #f8ac59 !important;
}

the problem is that all select2 has the orange border, and i need only that the select2 from "select" Input with required attribute. how can i solve this.

HTML

<select class="form-control form-control-sm" data-width="100%" required>
    <option>Selec.</option>
    <option>Prueba 2 max with</option>
    <option>Prueba 3</option>
    <option>Prueba 4</option>
    <option>Prueba 5</option>
</select>

Initialice:

$('select').each(function () {
        $(this).off('change');
        var width= $(this).attr("data-width") || '100px';
        $(this).select2({
            theme: 'bootstrap4',
            placeholder: "Buscar y Selecionar",
            width: width,
            dropdownAutoWidth: true
        });
    });

Solution

  • To solve the problem it was necessary to make some changes in the scrip's iniaicalization:

    $('select').each(function () {
            $(this).off('change');
            var width= $(this).attr("data-width") || '100px';
            $(this).select2({
                theme: 'bootstrap4',
                placeholder: "Buscar y Selecionar",
                width: width,
                dropdownAutoWidth: true
            });
            var x = this.required;
            if(x){
                $(this).next().children().children().each(function(){
                    $(this).css( "border-color", "#f8ac59" );
                });
            }
        });