1
I have a select option field and would like the user to click submit, the system color the field
When inspecting the element with Chrome I realized that Chosen put a style display: None and if you take it out it works, but that’s not what I want:
The object is if it is empty when you click the button, select option turn red
Following example:
var setores = [
"Almoxarifado",
"Controladoria",
"Administrativo",
"Tecnologia de Informação"
];
var i = 0;
setores.forEach(function(item){
i++;
addOption(i, item);
});
function addOption(i, valor) {
var option = new Option(valor, i );
var select = document.getElementById("cmb-setor");
select.add(option);
}
$('#cmb-setor').trigger("chosen:updated");
$('.btn-save').on('click', function(){
var id = $('#cmb-setor').val();
console.log("Setor: "+id);
if( id == 0 ){
$('select[id="cmb-setor"]').css("border-color","red");
// $('select[id="cmb-setor"]').css({"border-color":"red", "display":"block"});
}
});
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.2/chosen.jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.2/chosen.css" rel="stylesheet"/>
<div class="form-group">
<select class=" form-control" id="cmb-setor" data-placeholder="Escolha um setor">
<option value="0"></option>
</select>
</div>
<button class="btn btn-primary btn-save">Salvar</button>
<script>
$('#cmb-setor').chosen( {allow_single_deselect: true} );
</script>
And if in case you have more than one combobox ,as it would be?
– adventistaam
I’m trying like this :
$('#cmb-setor.chosen-container-single').addClass('required');
and it’s not working– adventistaam
I found out! Inside the class
choosen-container
Chosen adds an extra string to the id. Soid=cmb-setor_chosen
from there it would be $('#cmb-setor_chosen'). addClass('required') ; Thanks– adventistaam