Victor Mora Victor Mora - 1 month ago 7
jQuery Question

Filter Flask Rendered HTML Table Using jQuery

I am trying to render a jinja2 template that displays an html table and then dynamically filters the table but I cannot get it to work correctly. The table renders as expected but the search box used to dynamically filter the table isn't working. For reference, the script in layout.html works in a non-flask app.

Here is my flask app (message_log.py):

import pandas as pd
from flask import Flask, render_template
pd.set_option('display.max_colwidth', -1)

app = Flask(__name__)
message_log = pd.read_csv('data.csv')
table = message_log.to_html().replace('<tbody', '<tbody id="fbody"')

@app.route("/")
def show_table():
return render_template('index.html', table=table)

if __name__ == "__main__":
app.run(debug=True)


index.html:

{% extends "layout.html" %}
{% block body %}
Search (Case Sensitive): <input type="text" id="search" placeholder="type to search"/>
{{ table|safe }}

{% endblock %}


layout.html:

<!doctype html>
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
// Search functionality
$("#search").keyup(function () {
//split the current value of searchInput
var data = this.value.split(" ");
//create a jquery object of the rows
var jo = $("#fbody").find("tr");
if (this.value == "") {
jo.show();
return;
}
//hide all the rows
jo.hide();

//Recusively filter the jquery object to get results.
jo.filter(function (i, v) {
var $t = $(this);
for (var d = 0; d < data.length; ++d) {
if ($t.is(":contains('" + data[d] + "')")) {
return true;
}
}
return false;
})
//show the rows that match.
.show();
}).focus(function () {
this.value = "";
$(this).css({
"color": "black"
});
$(this).unbind('focus');
}).css({
"color": "#C0C0C0"
});
</script>
<title>jQuery Example</title>
</head>

<body>
{% block body %}{% endblock %}
</body>
</html>

Answer

Move the second element to the bottom of index.html file just before the html tag closes. The jquery in your script was searching for an element that wasn't injected into your dom at the time that it was loaded.