I want to set a red border around each of my select box with jQuery. But it does not work out:
http://jsfiddle.net/jEADR/3795/
<script type="text/javascript" src="//code.jquery.com/jquery-1.8.3.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.css">
<select class="select" style="width:300px">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
<select class="select" style="width:300px">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
<script>
$(".select").select2();
$(".select").each(function() {
$(this).siblings().find(".select2-container").css({"border-color": "red", "border-weight":"5px", "border-style":"solid"});
});
</script>
Firstly, your code doesn't work because the select2-container elements are the siblings, so calling find() on them to get the children returns nothing. Simply remove the find() call, and give the selector to siblings(). Also note that you can shorten the border rule, like this:
$(".select").each(function() {
$(this).siblings(".select2-container").css('border', '5px solid red');
});
However, more importantly, you should note that using JS code for this is a little redundant when you can place the rule directly in your CSS code:
$(".select").select2();
.select2-container {
border: 5px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.css">
<select class="select" style="width:300px">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
<select class="select" style="width:300px">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
.select2-selection { border: 1px solid gold!important;}