Reputation: 31
I've made a script that searches by given filters. Everything works fine, except male / female search because the word female contains the word male in it. Selecting male gives me female results as well.
I've tried adding '\b' and '\s' before and after the gender selection in JS, both with single and double slashes. Here is the code below:
<div id="filters">
<h2>Filter Tables By</h2>
Topic:
<select id="topic_group" onchange="createSearchString();">
<option></option>
<option>Cancer</option>
<option>Smoking</option>
<option>Vaccinations</option>
<option>Health Screenings</option>
<option>Usual Place of Health Care</option>
</select>
Population of interest (Total, Male, Female):
<select id="popinterest_group" onchange="createSearchString();">
<option></option>
<option>Total</option>
<option>Male</option>
<option>Female</option>
</select>
</div>
<script src="/TemplatePackage/3.0/js/libs/jquery-datatables/jquery.dataTables.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#example').dataTable({
sDom:'<"nhis_search"f>t<"nhis_length"l> <"nhis_pagination"ip>',
aaSorting: [],
oLanguage: { sSearch: 'Additional search terms:' },
});
});
var searchString = new String();
function createSearchString() {
searchString = $('#topic_group').val() + ' ' + $('#popinterest_group').val() + ' ' + $('#outcomes_group').val();
$('#example_filter').find('input').val(searchString);
$('#example_filter').find('input').trigger('keyup');
}
</script>
Upvotes: 3
Views: 178
Reputation: 1706
Just add value in your filter option and then check the selected option when onchange, then use datatable filter to filter data based on column and filter
Note: Don't use search() method if your purpose is to filter data by using exact value
<div id="filters">
<h2>Filter Tables By</h2>
Topic:
<select id="topic_group" onchange="createSearchString();">
<option></option>
<option>Cancer</option>
<option>Smoking</option>
<option>Vaccinations</option>
<option>Health Screenings</option>
<option>Usual Place of Health Care</option>
</select>
Population of interest (Total, Male, Female):
<select id="popinterest_group" onchange="createSearchString();">
<option></option>
<option>Total</option>
<option value="0">Male</option>
<option value="1">Female</option>
</select>
</div>
<script src="/TemplatePackage/3.0/js/libs/jquery-datatables/jquery.dataTables.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var table = $('#example').dataTable({
sDom:'<"nhis_search"f>t<"nhis_length"l> <"nhis_pagination"ip>',
aaSorting: [],
oLanguage: { sSearch: 'Additional search terms:' },
});
});
function createSearchString() {
var gender = $('#popinterest_group').children("option:selected").val(); // get the option value
var filteredData = table
.column( 0 ) // index of column
.data()
.filter( function ( value, index ) {
if (gender == 0) return value == "male"
else if (gender == 1) return value == "female"
return value
} );
}
</script>
Upvotes: 1