I’m building my own WP theme and I try to avoid JS in WordPress like the plague because it’s hieroglyphics for me… And I still haven’t found a resource to learn correctly in a WP environment…. But there are two functions that I haven’t had the choice of until now… Sorting a table works well after getting help here. Now it’s filter this same table. I even tried to put the code directly in the footer.php without success. The code just doesn’t fire. The code does not come from me, it was found on the net.
HTML+PHP code from archive-challenge.php
<input id="search" class="text" type="text" placeholder="type text" >
<table id="table" class="resp">
<thead>
<tr>
<th onclick="sortTable(0)" scope="col" class="sortable"> Challenge </th>
<th onclick="sortTable(1)" scope="col" class="sortable"><i class="icon solid fa-mountain"></i> Nb. Sommets </th>
<th onclick="sortTable(2)" scope="col" class="sortable"><i class="icon solid fa-map"></i> Location </th>
</tr>
</thead>
<tbody>
<?php
$iteration =0 ;
while(have_posts()) {
the_post();
?>
<tr>
<td data-label="Challenge"
<?php
if ($iteration == 0) {
echo '>';
} else {
echo ' scope="row">';
}
?>
<a href="<?php the_permalink(); ?>" ><?php the_title(); ?></a>
</td>
<td data-label="Nb. Sommets">
<?php
$count = get_field('sommets-REL');
echo count($count);
?>
</td>
<td data-label="Location">
<?php
// ##################################
// Récupérer le Custom Field Location
$locations = get_field('location1');
if( $locations ):
$post = $locations[0];
setup_postdata($post);
the_title();
wp_reset_postdata();
endif;
?>
</td>
</tr>
<?php
$iteration++;
}
?>
<tbody>
</table>
Now the register in function.php
function ressources_montagnes() {
// #### JS
wp_register_script('main_js', get_template_directory_uri() . '/assets/js/main.js', array('jquery'),'0.1', true);
wp_enqueue_script('main_js');
}
add_action('wp_enqueue_scripts' , 'ressources_montagnes', 999);
And the JS in main.js
jQuery(document).ready(function($) {
// Write on keyup event of keyword input element
$("#search").keyup(function(){
_this = this;
// Show only matching TR, hide rest of them
$.each($("table tbody tr"), function() {
if($(this).text().toLowerCase().indexOf($(_this).val().toLowerCase()) === -1)
$(this).hide();
else
$(this).show();
});
});
});
I know that main.js is correctly register because the only other script in that file is used to sort the table. And this script is working… But not the filter one.
I’ve tried with # before table selector, i’ve tried only TR, but nothing seem to work…
HELP!!!!
f.soucy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.