I've got a click handler that adds the parents data-attribute to an array, which works beautifully. I do however want to continue to add to my existing code.
I want to try add some more logic in there to build the array if the page loads with some of the items already selected. I'm just not sure on how to go about this.
I'm adding an is-checkedclass to my anchor on click, so I'm trying to first check when the page loads, if the class is already been assigned.
HTML
<div class="search-data__filter filter-open">
<div class="filter__header">
<h4>Brand</h4>
</div>
<ul>
<li data-filter="prada">
<a href="#" class="chkbox is-checked">Prada</a>
</li>
<li data-filter="oakley">
<a href="#" class="chkbox">Oakley</a>
</li>
<li data-filter="ray-ban">
<a href="#" class="chkbox is-checked">Ray-Ban</a>
</li>
<li data-filter="nike">
<a href="#" class="chkbox">Nike</a>
</li>
</ul>
</div>
jQuery:
$(document).ready(function (){
var checkbox = $(".chkbox"); //the anchor class for headers
var filterHead = $(".filter__header"); //what are our filter head classes
var criteria = []; // new array
//controls the opening of the filter headers
filterHead.on("click", function(e){
$(this).parent("div").toggleClass("filter-open");
});
//build array of this data-type
var array = checkbox.parent("li").attr('data-filter');
//not quite doing what I thought... returns 'm' 'e' 'n' 's'
for (var i = 0; i < array.length; i ++) {
console.log(array[i]);
}
checkbox.on("click", function(e){
$(this).toggleClass("is-checked");
//if the data attr is already in the array remove it, else add it
if (criteria.indexOf(array)!=-1){
criteria.splice(criteria.indexOf(array),1);
} else{
criteria.push(array);
}
console.log(criteria);
$.get( "/_ajax/_editir_ecommerce_search.aspx?theData=" + criteria + "theText" + $('#search-data__specific').val(), function( data ) {
$( ".search-data__returned" ).html( data );
console.log( "Load was performed." );
});
//prevent the hash of the anchor from
//sending you to top of screen
e.preventDefault();
});
});
However my attempt above to introduce the array variable outside of my click event means my click no longer works.
A working example might make things easier to look over, which you can find here
data-filterof the anchors with classis_checkedadded to your criteria on page load?console.log(array)aftervar array = checkbox.parent("li").attr('data-filter');to test what you have inside?is-checkedclass. I hope I'm explaining things a little better.