Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove css if an input field is empty

Tags:

jquery

css

I am making a button appear providing there is content in an input field, which works fine. However, if I remove all of the content it remains because I am not sure on how to reverse the process on some kind of toggle. Here is where I am at with it at the moment:

$(document).ready(function(){
    $("#issueField").keydown(function(){
        $("#issueTick").css("opacity", "1");
    });    
});

My question is, is there a way to toggle this so that if the input is empty the opacity will be set back to 0?

like image 335
danjbh Avatar asked Jan 22 '26 12:01

danjbh


1 Answers

You can use +!!$(this).val() for the CSS opacity value. This will be either 0 or 1 depending on whether there is text content in your input.

I would also suggest to listen to the input event instead of the keyup event, as the first will also trigger on other ways to change the input (mouse, context menu...):

$(document).ready(function(){
    $("#issueField").on("input", function(){
        $("#issueTick").css("opacity", +!!$(this).val());
        
    }).trigger("input");    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="issueField">
<div id="issueTick" style="background: yellow">issue tick</div>
like image 102
trincot Avatar answered Jan 24 '26 04:01

trincot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!