I have a filter function whereby a user can check one or multiple amenities and get the values which will be sent to the database using AJAX.
In this case upon clicking one checkbox I also want to get the values of the other checkboxes if they are checked.
On clicking the #balcony
input I will get the value of the balcony, also when I click the #wifi
checkbox I want to get the ‘yes’ value
How can I achieve this? I have tried the following logic but it doesn’t work.
$("#balcony").on('click', function() {
var balcony = $(this).val();
var wifi = $("#wifi").prop('checked');
var parking = $("#parking").prop('checked');
var generator = $("#generator").prop('checked');
console.log(wifi);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="card-body">
<div class="card-title" style="margin:0px; padding:3px;">
<h5 style="color: black; font-size:18px;">Amenities</h5>
</div>
<div class="checkbox checkbox-success">
<input type="checkbox" name="filterbalcony" value="yes" id="balcony">
<label for="rentalcat" class="control-label">Balcony</label>
</div>
<div class="checkbox checkbox-success">
<input type="checkbox" name="filtergenerator" value="yes" id="generator">
<label for="rentalcat" class="control-label">Generator</label>
</div>
<div class="checkbox checkbox-success">
<input type="checkbox" name="filterwifi" value="yes" id="wifi">
<label for="rentalcat" class="control-label">Wifi</label>
</div>
<div class="checkbox checkbox-success">
<input type="checkbox" name="filterparking" value="yes" id="parking">
<label for="rentalcat" class="control-label">Parking</label>
</div>
</div>
2
Answers
You are only checking if the
checkbox
is checked or not, you can either usevar wifi = $("#wifi").prop('checked') ? 'yes' : 'no';
or
var wifi = $("#wifi:checked").val();
Beware that this will return undefined if wifi is not checked
You can try below snippet. I have added class to input boxes and just modified event to
change