Reputation: 25
I'm trying to make a div apear and disapear when typing in a regular input box. It should toggle to be visible only when the input has content, without having a button or an action outside the input box.
I've tried several options. When using .change it only updates the state of the div when I click the mouse outside of the input.
If I am using .val() == '' and .addClass if empty it does not toggle the state of the class when the value change.
I'll add the latest try I had, with .val(),
<div id="bd_search">
<div class="inner">
<input class="inptsrch" type="text" placeholder="Perform your search here.." />
</div>
</div>
<div id="bd_search_res">
<div class="inner">
<div class="res_col1">
Results from Category A.
</div>
<div class="res_col2">
Results from Category B.
</div>
</div>
</div>
$(document).ready(function(){
if($('input.inptsrch').val() == ''){
$( "#bd_search_res" ).addClass( "srcresHide" );
}
});
Anybody have experience with this behavior through jquery?
https://jsfiddle.net/johneilif/r4uh3dag/
Upvotes: 1
Views: 38
Reputation: 9476
You can do this way: https://jsfiddle.net/r4uh3dag/15/
$("input.inptsrch").keyup(function(){
if($(this).val() != ''){
$( "#bd_search_res" ).show();
}
else{
$("#bd_search_res").hide();
}
});
Upvotes: 1
Reputation: 6565
Use keyup
event to check when the user press any key and the input has some value or not (if else
conditions here do that) and based on the val()
of the input, if it is empty or not, add or remove the desired class.
$(document).ready(function(){
$("input.inptsrch").keyup(function(){
if($(this).val() == ''){
$( "#bd_search_res" ).addClass( "srcresHide" );
}
else{
$("#bd_search_res").removeClass( "srcresHide" );
}
});
});
Upvotes: 0