I have been working on a filter function in jQuery for a simple unordered list. Each list is inside a block with a filter that can be modified in the back-end (Wordpress) to filter out specific strings. The filter also has a reset button to set it back to the original state.
Now I've been asked to make this a repeatable list. Repeating the list itself wasn't a problem but the filter now filters out items in all existing lists.
So the filter does work but it gets a bit overexcited filtering out all elements that have the class filter-list_item. I thought adding a number to the class on the parent div on each loop and then adding a for loop in jQuery to target these specific classes would fix this. Hence the $list_count and listCount variables. This however does the exact same thing and still affects all lists. I'm not sure why. Any help on how to make it so that the filters only filter out items in their corresponding lists would be much appreciated.
This is the current jQuery for the filter function:
$(document).ready(function (){
// Content filter
var lists = $(".filter-list").length;
for(var listCount = 0; listCount < lists; ) {
$(".filter-list-"+listCount).find(".content-filter").change(function() {
// Retrieve the option value and reset the count to zero
var search = $(this).val(), count = 0;
$(".filter-list_item").each(function(){
// Remove item if it does not match the value
var string = this.innerText;
var found = strSearch(search.toLowerCase(), string.toLowerCase());
if (found) {
$(this).css("display", "block");
// Show the list item if the value matches and increase the count by 1
count++;
} else {
$(this).css("display", "none");
}
// Show reset button
if($(this).index() > 0) {
$(".filter-reset").addClass("active");
}
});
// Update the count
if(count == 0) {
$(".filter-select-results").text("No results for " +search);
} else if(count > 0) {
$(".filter-select-results").text('');
}
});
// Reset filter
$(".filter-reset").click(function() {
$(".content-filter").prop('selectedIndex',0);
$(".filter-list_item").css("display", "block");
$(".filter-reset").removeClass("active");
$(".filter-select-results").text('');
});
listCount++;
}
});
// Search function
function strSearch(search, string) {
var n = string.search(search);
if(n >= 0) {
return true;
}
return false;
}
And this is the PHP used to build the lists
<?php
$list_count = 0;
foreach ($layout['list'] as $list) { ?>
<div class="container filter-list filter-list-<?php echo $list_count++; ?>">
<div class="title-wrapper">
<h2><?php echo $list['title']; ?></h2>
<?php echo $list['description'];
// Content filter
if($list['content_filter'] == true) { ?>
<div class="filter-container">
<button class="filter-reset"><i class="fa-icon fa fa-undo"></i></button>
<select class="content-filter" name="filterselect">
<option value="all" disabled selected>Selecteer een locatie</option>
<?php foreach($list['filter_options'] as $filter) { ?>
<option value="<?php echo $filter['option']; ?>"><?php echo $filter['option']; ?></option>
<?php } ?>
</select>
</div>
<?php } ?>
</div>
<div class="filter-select-results"></div>
<ul class="filter-list_items">
<?php foreach($list['list_items'] as $list_item) { ?>
<?php if( $list_item['link'] ) { ?>
<li class="filter-list_item"><?php echo $list_item['item']; ?></li>
<?php } else { ?>
<li class="filter-list_item">
<span><?php echo $list_item['item']; ?></span>
</li>
<?php } ?>
<?php } ?>
</ul>
</div>
Replace $(".filter-list_item").each(function(){ with $(this).closest(".filter-list").find(".filter-list_item").each(function(){
This is assuming .content-filter-element is part of a .filter-list. closest then navigates to the first parent satisfying the condition. Whether that condition holds is a bit unclear from the php code you showed.
Related
So, I'm trying to create a filter for this list of stores, so only the ones with content that is equal to the value of the input box will display. Unfortunately, my filter does not work correctly. For one, whatever I type in the input box causes all of my store elements to add the 'display' class, which causes my items to receive the style 'display: none;'. Secondly, it's not updating every time a key is pressed.
HTML:
<li class="p-3 clearfix store display">
<div class='float-left w-50'>
<div class='mb-1'><strong>Store Number:</strong><span class="store-info">
<?php
if (strlen($row['store_num']) < 4) {
if (strlen($row['store_num']) == 3) {
echo '0' . $row['store_num'];
} else if (strlen($row['store_num']) == 2) {
echo '00' . $row['store_num'];
}
} else {
echo $row['store_num'];
}
?>
</span></div>
<div class='mb-1'><strong>Store Name: </strong><span class='store-info'><?php echo $row['store_name']; ?></span></div>
<div class='clearfix mb-1'>
<p class='float-left'><strong>Address: </strong></p>
<span class='d-block store-info float-left'><?php echo $row['store_street']; ?></span>
<br>
<span class='d-block store-info float-left'><?php echo $row['store_city']; ?>, <?php echo strtoupper($row['store_state']); ?> <?php echo $row['store_zip']; ?></span>
</div> <!-- mb-1 -->
</div> <!-- float-left -->
<div class="float-left w-50 clearfix">
<div class="d-inline float-right">
<div class='mb-1'>
<strong>Time Zone: </strong><span class='time-zone store-info'><?php echo strtoupper($row['time_zone']); ?></span>
</div>
<div class='mb-1'>
<strong>Current Time: </strong><time>3:45pm</time>
</div>
<div class='mb-1'>
<strong>Phone Number:</strong><span class='store-info'>
<?php
$phone = $row['store_phone'];
$area = substr($phone, 0, 3);
$prefix = substr($phone, 4, 3);
$line = substr($phone, 6, 4);
echo '(' . $area . ') ' . $prefix . '-' . $line;
?>
</span>
</div>
<div class='mb-1'>
<strong>Fax Number:</strong><span class='store-info'>
<?php
$phone = $row['store_fax'];
$area = substr($phone, 0, 3);
$prefix = substr($phone, 4, 3);
$line = substr($phone, 6, 4);
echo '(' . $area . ') ' . $prefix . '-' . $line;
?>
</span>
</div>
</div> <!-- d-inline -->
</div> <!-- float-right -->
</li> <!-- clearfix -->
JavaScript:
var search = document.getElementById('search');
var stores = document.querySelectorAll('.store');
search.addEventListener('keyup', function (e) {
var data = e.target.value.toLowerCase();
stores.forEach(function(store) {
var spans = document.querySelectorAll('.store-info');
for(var i = 0; i < spans.length; i++) {
if (spans[i].innerText.toLowerCase() != data) {
store.classList.remove('display');
} else {
store.classList.add('display');
}
}
});
});
If I understand your question correctly, you could make the following changes to your javascript to resolve the issues you're facing. Please see comments in code for explaination of what's going on:
search.addEventListener('keyup', function (e) {
var query = e.target.value.toLowerCase();
if (search.value.length >= 0) {
search.classList.add('focused');
label.classList.add('focused');
} else {
search.classList.remove('focused');
label.classList.remove('focused');
}
// recommend performing this query in the keyup event to ensure
// that you're working with the most up to date state of the DOM
var stores = document.querySelectorAll(".store");
stores.forEach(function(store) {
// query .store-info from current store
var spans = store.querySelectorAll(".store-info");
// hide the store by default
store.style.display = 'none';
for (var i = 0; i < spans.length; i++) {
var storeInfoText = spans[i].innerText.toLowerCase();
// consider revising search logic like so
if (storeInfoText.indexOf(query) !== -1 || !query) {
// display the store if some match was found
store.style.display = 'block';
}
}
});
});
Link to working jsFiddle here
I think your issue with it showing everything is because of the add remove... if a store already has display it will re add it and then only remove it once where as if it doesn’t you will get an error so try toggle
var search = document.getElementById('search');
var stores = document.querySelectorAll('.store');
search.addEventListener('keyup', function (e) {
var data = e.target.value.toLowerCase();
stores.forEach(function(store) {
var spans = document.querySelectorAll('.store-info');
spans.filter(span=>{
if(span.innerText.toLowerCase().includes(data)){
store.classList.toggle('display');
}else{store.classList.toggle('display')
})
});
I am using js and php to build an app. I've used a foreach loop in php to create buttons for each row fetched from mysql table. Each button has a unique value (row id).
If someone clicks on of the buttons (each with unique id), there will be a total likes count that holds how many times a button is clicked.
If we have three buttons, and button 1 is clicked, then total likes will be increase by 1. if the same button is clicked again, then the value would decrease by 1.
However, if two buttons of different values are clicked, the total likes add.
When using js, I cant get each button id to pass to the js function loaded from the foreach loop. only the last button value loads to the js function.
Here is what i've tried. the js works but it doesnt apply to each button of the foreach loop.
My Code
<?php foreach($values as $value){
$value['button_id'];
<!-- button --->
<button id="button"
class="button-<?= $value['button_id']; ?>"
value="<?= $value['button_id']; ?>"
onclick="showUser(this.value)" >LIKE
</button>
<!-- button --->
} ?>
<script>
var i = parseInt(document.getElementById('button').value, 10);
var x = i;
function showUser(this.value) {
/// changing value //
if (x == i){
i++;
document.getElementById('button').value = i;
}
else {
i = x;
document.getElementById('button').value = i;
}
}
</script>
Here is an illustration explaining what I mean
Thanks in advance
<script>
var likes = new Array();
function calc(value) {
if(likes[value] == 0 || !likes[value]) {
likes[value]=1;
} else {
likes[value]=0;
}
var sum=0;
for(i=0; i<likes.length; i++) {
if(likes[i]==1){ sum ++ }
}
document.getElementById("total").innerHTML = sum;
}
</script>
<div id=total>0 </div>
<?php
$values = [1,2,3]; //here you can generate values
foreach($values as $value){
?>
<button id="button"
class="button-<?php echo $value; ?>"
value="<?php echo $value; ?>"
onclick="calc(<?php echo $value; ?>)" >LIKE
</button>
<?php
} ?>
<script>
var i = parseInt(document.getElementById('button').value, 10);
var x = i;
function showUser(this.value) {
/// changing value //
if (x == i){
i++;
document.getElementById('button').value = i;
}
else {
i = x;
document.getElementById('button').value = i;
}
}
</script>
Well im adding to database some records but i dont like the way i did and wanted to make something way easier for the user and better.
What i did was: http://i.imgur.com/AYrPyCn.jpg
And what i want is: http://i.imgur.com/aKNBTtO.jpg
Well i guess i know how to create the divs geting all the images from database and the horizontal scroll bar but what i dont know is when i select the image that id from image will appear on the input create by me.
Help needed.
Code from what i have:
<select name="id_artigo" id="attribute119">
<?php
do {
?>
<option value="<?php echo $row_artigos['id_artigo']?>" ><?php echo $row_artigos['id_artigo']?></option>
<?php
} while ($row_artigos = mysql_fetch_assoc($artigos));
?>
</select>
<div id="editimg"><p><img src="images/artigos/1.png" id="main" /></p></div>
Js:
$('#attribute119').change(function () {
$('#main').attr('src', 'images/artigos/' + $('#attribute119 :selected').text() + '.png');
});
You can use jQuery slideshow plugin like jcarousel or jssor.
Just do a google search on "jQuery slideshow" or "jQuery carousel".
I recommend you to use jcarousel.
Anas
Since you don't want it to look like a drop-down any more, replace the drop-down with a hidden field, which will hold the ID of the item they select:
<input type="hidden" name="id_artigo" />
(for testing you could use type="text" instead)
Give each of your images a data-id-artigo attribute:
<img class="artigo_img" src="images/artigos/1.png" data-id-artigo="1">
When an image is clicked, update the hidden ID's value:
$('.artigo_img').on('click', function() {
var idArtigo = $(this).data('idArtigo'); // get the artigo ID from the `data-` attribute
$('[name="id_artigo"]').val(idArtigo); // update the value of the hidden field
});
When the form is submitted, id_artigo will be equal to the selected item, just like before.
I see now that you just want to select 1 image, this answer is for selecting multiple images.
(not tested, so there might be some errors)
<style>
.img_holder
{
height:100px;
clear:both;
}
.floating_img
{
float:left;
width:100px;
height:100px;
}
.img_selected
{
border:1px solid black;
}
</style>
<div class="img_holder">
<?php
$img_id_arr = array();
do {
$selected = true; //<--implement if they are selected
$selected_class = '';
if($selected)
$img_id_arr[] = $row_artigos['id_artigo'];
$selected_class = ' img_selected';
}
?>
<div class="floating_img<?php echo $selected_class; ?>" onclick="toggle_img(<?php echo $row_artigos['id_artigo']; ?>);"><img src="images/artigos/<?php echo $row_artigos['id_artigo']; ?>.png" id="main" /></div>
<?php
} while ($row_artigos = mysql_fetch_assoc($artigos));
?>
<input typ="hidden" id="my_selected_images" name="my_selected_images" value="<?php echo implode(';',$img_id_arr); ?>">
<script>
function toggle_img(img_id)
{
var selected_imgs = $('#my_selected_images').value;
var img_arr = selected_imgs.split(";");
var found = false;
var new_arr = [];
for (i = 0; i < img_arr.length; i++) {
if(img_id == img_arr[i])
{
found = true;
//deselect img
}
else{
//leave other item untouched
new_arr.push(img_arr[i]);
}
}
if(!found)
{
new_arr.push(img_id);
//select img
}
$('#my_selected_images').value = new_arr.join(';');
}
</script>
</div>
I have this problem. I can't figure what's wrong with my code. All i need to do is to hide the inline edit image button whenever the $principal_amt==$balance_amt but my code does nothing. Here's my code:
// Edit image button:
<td <?php echo $rowclass; ?>>
<?php echo $html->linkWithImage('Edit','cashadvance/update/' . $cashadvance["id"], array(), 'editicon.png', array('class' => 'try')); ?>
</td>
//JS:
$("#principal_amt").change(function(){
var principal = $("#principal_amt").val();
$("#balance_amt").val(principal);
if("#balance_amt" == "#principal"){
$('.try').show(true);
}
else{
$('.try').hide(true);}
});
you are comparing with the the ID's not there values in if("#balance_amt" == "#principal")
that should be :
$("#principal_amt").change(function(){
var principal = $("#principal_amt").val();
$("#balance_amt").val(principal);
if($("#balance_amt").val() == principal){
$('.try').show(true);
}
else{
$('.try').hide(true);}
});
you compare two different string:
if("#balance_amt" == "#principal"){
This means: if the string #balance_amt = #principal then.. but this is always false.
If I understand well your problem try to change to this your code:
$("#principal_amt").change(function(){
var principal = $("#principal_amt").val();
$("#balance_amt").val(principal);
if($("#balance_amt").val() == principal){
$('.try').show(true);
}
else{
$('.try').hide(true);
}
});
In this case is always true...
In my custom Wordpress theme I am trying to animate all my table "nodes" in as the page loads simultaneously.
I can get this animation to work by applying the animation to each element individually but since trying to automate this process the animation fades all my nodes in at the same time and I do not understand why.
The below code generates my nodes...
<div class="span12 news-tiles-container">
<div class="row span12 news-tiles-inner">
<?php
$node_id = 1;
$node_size_id = 1;
?>
<?php if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php
if($node_size_id > 3) {
$node_size_id = 1;
}
?>
<a href='<?php the_permalink(); ?>'>
<div class='node node<?php echo $node_id ?> size<?php echo $node_size_id ?>'
style='background-image: url(<?php the_field( 'thumbnail' ); ?>);'>
<div id="news-caption" class="span12">
<p class="span9"><?php the_title(); ?></p>
<img class="more-arrow" src="<?php bloginfo('template_directory'); ?>/images/more-arrow.png" alt="Enraged Entertainment logo"/>
</div>
</div>
</a>
<?php
$node_size_id++;
$node_id++;
?>
<?php endwhile; endif; ?>
</div>
</div>
And I am using the following code to control there animate in
$(document).ready(function(){
// Hide all of the nodes
$('.node').hide(0);
// Local Variables
var node_id = 1;
var nodes = 10;
var i = 0;
while(i <= nodes)
{
$('.node'+node_id).hide(0).delay(500).fadeIn(1000);
node_id+=1;
nodes--;
} });
I assume it is something to do with my while loop, but the node counter increments successfully so it should be applying the animation to node1 then node2 then node3 and so on.
Thanks in advance
Alex.
Here's a generic plugin that will perform any animation you want, in sequence, on a jQuery collection of elements:
(function ($) {
$.fn.queueEach = function (func) {
var args = [].slice.call(arguments, 1); // array of remaining args
var els = this.get(); // copy of elements
(function loop() {
var el = els.shift();
if (el) {
$.fn[func].apply($(el), args).promise().done(loop);
}
})();
return this;
}
})(jQuery);
Usage:
$('.node').queueEach('fadeIn', 'slow');
Working demo at http://jsfiddle.net/alnitak/D39Cw/
Use your brandy dandy .fadeQueue(): working jsFiddle
$.fn.fadeQueue = function(){
$(this).fadeIn(function(){
if(!$(this).is(':last-child')) // making sure we are not done
$(this).next().fadeQueue();
});
}
This will wait for the callback of .fadeIn() for each div before moving to the next one..
Probably not as elegant, but still works:
$(document).ready(function(){
$('.node').hide();
$('.node').each(function(index,elem){
setTimeout(function(){$(elem).fadeIn(1000);},1000*index);
});
});
jsFiddle here