I have 3 columns, each one has a select of a form. I am trying to have a class "clicked" to my div that has "col-12" depending on the select item that I am currently using, and only if I chose an option. Here's the code that I have until the moment but apparently the jquery isn't being applied to my tag, is it a default behavior?
PS: The code works when I select only the .form-control class, but I dont want this, I just want it to be applied if the user actually click on any option inside the select element.
JQUERY:
function(){
$('.form-control option').on('click', function(){
$(this).closest('.col-12').addClass('clicked');
});
}
HTML My html has 4 columns like that (only changing the options inside each one)
<div class="row">
<div class="col-12 col-sm-6 col-lg-3 arrow--custom">
<select class="form-control" id="room" name="room">
<option value="" selected="" disabled="">Nombre de chambre</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
</div>
The problem is that you're listening on the element, and you need to liste on instead.
When the value of the changes, you add the class. Here's a working snippet, where the clicked class will add a red border so that it is visible:
(function(){ $('select.form-control').on('change', function(){ $(this).closest('.col-12').addClass('clicked'); }); })();
.clicked select { border: red 2px solid; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="row"> <div class="col-12 col-sm-6 col-lg-3 arrow--custom"> <select class="form-control" id="room" name="room"> <option value="" selected="" disabled="">Nombre de chambre</option> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> </div> </div>
You can't register events on an <OPTION>. Instead, you should check for 'change' on your <SELECT>
function(){
$('.form-control').on('change', function(){
$(this).closest('.col-12').addClass('clicked');
});
}
Applying this changes to my code, made it work:
function(){
$('.form-control').on('change', function(){
$(this).closest('.col-12').addClass('clicked');
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.