I am trying to understand how to create a function that will allow me to filter a list of offers based on serialized form data and the data attributes of each offer.
Here is my example but I just can not come up with a way to condition multiple data attributes inside my filterOffers() function. I would deeply appreciate it if someone could help me to go in the right direction.
The key point here is that there can be many different checkboxes and options as well as many different data attributes, that is why I am trying to find a way to filter by multiple data attributes.
JavaScript
$(function(){
$('form').submit(function(e){
e.preventDefault();
var formData = $(this).serializeArray();
filterOffers(formData);
});
});
function filterOffers(attributes){
$(".offer").hide().filter(function(i) {
// How to filter the list based on given options and data attributes?
// If I reach this point then the offer is shown.
return true;
}).show();
}
HTML
<form>
<input type="checkbox" name="monthly" /> Paid monthly
<input type="checkbox" name="unlimited" /> Unlimited data
<input type="submit" />
</form>
<div class="offer" data-monthly="true" data-unlimited="false">Offer 1</div>
<div class="offer" data-monthly="true" data-unlimited="true">Offer 2</div>
<div class="offer" data-monthly="true" data-unlimited="true">Offer 3</div>
Try this:
$('form').submit(function (e) {
e.preventDefault();
var formData = new FormData(this);
filterOffers(formData.getAll('p[]'));
});
function filterOffers(attributes) {
$(".offer").hide();
for (let i = 0; i < attributes.length; i++) {
const attribute = attributes[i];
$(".offer[data-"+ attribute+"=true]").show();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="p[]" value="unlimited" /> Unlimited data
<input type="checkbox" name="p[]" value="monthly" /> Paid monthly
<input type="submit" />
</form>
<div class="offer" data-monthly="true" data-unlimited="false">Offer 1</div>
<div class="offer" data-monthly="true" data-unlimited="true">Offer 2</div>
<div class="offer" data-monthly="true" data-unlimited="true">Offer 3</div>