For a custom framework like Bootstrap select https://silviomoreto.github.io/bootstrap-select/ how do I change the border color of a select box in Javascript?
I tried th
If you see the DOM element generated by bootstrap-select
, it actually hides the original select
element and creates its own structure with div
,span
and buttons
. There isn't any official documentation provided to change its border
, but as a workaround you could do it as below:
You need to change border of the button
whose class
is btn dropdown-toggle btn-default
, which is generated by bootstrap-select
. Since the element created will not be given any id
we will make use of its class
with document.getElementsByClassName("classnames")[0]
document.getElementsByClassName("btn dropdown-toggle btn-default")[0].style.borderColor = "red";
Update
Explanation in comments.
$(document).ready(function() {
//add a change event to each selectpicker
$('.selectpicker').selectpicker().on('change', function() {
var id = $(this).attr('id'); //get current element's id
var selected = $(this).find("option:selected").val(); //get current element's selected value
var condition = false; //default false to form valid
$(this).selectpicker('setStyle', 'btn-danger', selected == "" ? "add" : "remove");
if (id == "box") {//if its first select box
condition = !(selected == 2 || selected == ""); //check if its value==2 or value=="" so that form validation depends of respective selects
$("#box2").selectpicker(selected == 2 ? "show" : "hide").val("");
//show or hide box2 based on selected val
$("#box2").selectpicker('setStyle', 'btn-danger',"remove");
//remove danger from 2nd selectpicker when its hidden or shown
} else {
condition = !(selected == "");
//if its box 2 check if any value is selected
}
$(this).closest('form').data('valid', condition);
//set it to form's data-valid attribute
});
$("#box2").selectpicker('hide');//default hide on page load
//form submit event instead of validate() inline function
$("form").on("submit", function(e) {
e.preventDefault();//prevent default action of submit
var isValid = $(this).data('valid');//check if its valid
if (!isValid) {
//if not valid loop through each selectpicker
$.each($('.selectpicker'),function(){
var selected=$(this).val();
//check appropriate values for each select and set/remove the btn-danger class for respective selectpickers
$(this).selectpicker('setStyle', 'btn-danger', selected == "" ? "add" : "remove");
})
}
else{
alert(isValid);
//Submit your form
}
})
});