I have a table which include names, the last name of each entry needs to be truncated ex. Miles Davis becomes Miles D.
I achieve this with the following JS:
$('.trunc-name').each(function (d, td) {
$(td).text($(td).text().replace(/^(\S+)\s+(\S).*/, '$1 $2.'));
});
and the td
class is set to trunc-name
:
<td class="trunc-name"><?php foreach ($resident_name_terms as $object) { echo $object->name; } ?></td>
Those table contents (which are actually WP taxonomy terms) are filterable via a select form - the options of which are getting truncated too.
Select:
if( $terms = get_terms( array(
'taxonomy' => 'resident_name',
'orderby' => 'name'
) ) ) :
echo '<select name="resident_name_filter"><option value="" selected="selected">' . __( 'All Residents', 'mv' ) . '</option>';
foreach ( $terms as $term ) :
echo '<option class="trunc-name" value="' . $term->term_id . '">' . $term->name . '</option>';
endforeach;
echo '</select>';
endif;
So far everything works fine. The problem is that when I change criteria via a select option for that column (built with AJAX), the newly outputted values are not truncated.
Query Params:
$relation = 'AND';
$params = array();
$args['tax_query']['relation'] = $relation;
foreach ( $taxonomies as $tax ) {
if( isset( $_POST[ $tax . '_filter' ] ) && !empty( $_POST[ $tax . '_filter' ] ) ) {
$args['tax_query'][] = array(
'taxonomy' => $tax,
'field' => 'id',
'terms' => $_POST[ $tax . '_filter' ],
);
}
};
Loop:
$query = new WP_Query( $args );
if( $query->have_posts() ) : ?>
<table style="width:100%" id="incident-reports">
<tr>
<th>Resident</th>
</tr>
<?php
while( $query->have_posts() ): $query->the_post();
$resident_name_terms = get_the_terms( $post->ID, 'resident_name' );
?>
<tr>
<td class="trunc-name"><?php foreach ($resident_name_terms as $object) { echo $object->name; } ?></td>
</tr>
<?php endwhile; ?>
</table>
endif;
Any help is, as always, greatly appreciated!
You need to run the truncate code in the success:
function after it creates the new elements.
$.ajax({
...
success: function(response) {
... // code that adds the new HTML
$('.trunc-name').each(function (d, td) {
$(td).text($(td).text().replace(/^(\S+)\s+(\S).*/, '$1 $2.'));
});
}
});