I have element like this :
<input type="text" onkeyup="filter()" id="filter_data">
<div id="body">
<div class="child"> Text 1 </div>
<div class="child"> Text 2 </div>
<div class="child"> Text 1 </div>
</div>
I want to search the div text by input value.
I can search the data but.. how to show "data Not found" inside div body, if all child div is not have any data like input value.
答案 0 :(得分:5)
You could add an increment a variable (result
in my example) to know if there's any data found or not then show/hide
the message :
if( result === 0 ){
$('.empty_div').removeClass('hide');
}else{
$('.empty_div').addClass('hide');
}
function filter() {
var value = $('#filter_data').val();
var div_class = $('#body').find(".child");
var result = 0;
div_class.hide();
div_class.each(function() {
if ($(this).text().toUpperCase().indexOf(value.toUpperCase()) != -1) {
$(this).show();
result++;
}
});
if (result === 0) {
$('.empty_div').removeClass('hide');
} else {
$('.empty_div').addClass('hide');
}
}
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" onkeyup="filter()" id="filter_data">
<div id="body">
<div class="child"> Text 1 </div>
<div class="child"> Text 2 </div>
<div class="child"> Text 1 </div>
<div class="empty_div hide">No Data Found</div>
</div>
答案 1 :(得分:1)
Add one more div and fiddle: https://jsfiddle.net/thecreativedev/0k8ustrv/62/
JS
function filter() {
var value = $('#filter_data').val();
var div_class = $('#body').find(".child");
$('.nomatched').html('').hide();
div_class.hide();
var i =0;
div_class.each(function() {
if ($(this).text().toUpperCase().indexOf(value.toUpperCase()) != -1) {
$(this).show();
++i;
}
});
if(i == 0){
$('.nomatched').html('No matched data Found').show();
}
}
HTML
<input type="text" onkeyup="filter()" id="filter_data">
<div id="body">
<div class="child"> Text 1 </div>
<div class="child"> Text 2 </div>
<div class="child"> Text 1 </div>
<div class="nomatched" style="display:none"></div>
</div>