Trying to get my array to update onto the front end dynamically, when a user either adds/removes an item.
HTML/PHP for frontend below:
<div class="row">
<div class="col-12">
<div class="custom--css_pills">
<span class="tag filtering">Edit Products</span>
<span id="pills--container"></span>
</div>
<?php
$items = get_posts( array (
'post_type' => array('products'),
'posts_per_page' => -1
));
echo '<div class="enquire--surround_div">';
foreach($items as $item) {
echo '<input class="enquiry--add_chk" type="checkbox" value="'.$item->post_title.'" id="'.$item->post_title.'" />
<label for="'.$item->post_title.'">'.$item->post_title.'</label>';
}
echo '</div>';
?>
</div>
</div>
So far, I set my array
var pills = ["test","test2"];
Then setup a function which loops through this array and echos out a div, with the array item and a close icon
function looparray(){
var str = '';
pills.forEach(function(pill) {
str += '<div class="tag">'
str += '<span>' + pill + '</span>';
str += '<span class="tag-exit"></span>';
str += '</div>';
});
// Echo
document.getElementById("pills--container").innerHTML = str;
}
then call this function on load
looparray();
Then I have an onclick, for the radio buttons (Front end). Which will add to the array or remove depending if the checkbox is checked
$('.enquiry--add_chk').click(function(){
$valuetoaddcolour = $(this).next();
$valuetoaddcolour.toggleClass('enquiry--tabs_colour')
$valuetoadd = $(this).next().text();
if ( $(this).is(':checked')) {
console.log('notfilled');
pills.push($valuetoadd);
console.log(pills);
}
else{
pills.splice( $.inArray($valuetoadd, pills), 1 );
console.log(pills);
}
looparray();
});
And then an on close, to remove the selected from the array.
//On close..
$('.tag-exit').click(function() {
$valuetoremove = $(this).parent(); // Get parent to hide (surround div)
$valuetoremovetext = $(this).parent().text(); // Get text to remove from array
// remove from array
pills.splice( $.inArray($valuetoremovetext, pills), 1 );
$valuetoremove.hide(); // Hide the pill
looparray();
});
now the issue is, when I first select a remove, it will run fine. If i then add an item, then try to remove via the .tag exit, it doesn't run the function. I've narrowed it down to the looparray(); causing the issue, but can't see what the issue is. All i can think is it's wiping the data and re-adding, which may cause an issue with pre-defined functions?
I've put a little codepen together to give a better understanding. https://codepen.io/anon/pen/QoQrZw