danjbh
danjbh

Reputation: 615

How to remove css if an input field is empty

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?

Upvotes: 3

Views: 248

Answers (4)

trincot
trincot

Reputation: 350310

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>

Upvotes: 6

Vinaysingh Khetwal
Vinaysingh Khetwal

Reputation: 121

Try this

    $(document).ready(function()
    {
      $("#issueField").keydown(function()
      {
         if($('#issueField').val() == "") 
           {
               $("#issueTick").css("opacity", "1");
           }
        else
          {
               $("#issueTick").css("opacity", "0.1");
          }
     })
   });

Upvotes: 1

Osama
Osama

Reputation: 3040

you have to set a blur event to check if the value of textbox is empty so it will return the opacity to 0 after blur from it

$(document).ready(function(){
    $("#issueField").keydown(function(){
        $("#issueTick").css("opacity", "1");
    });    
$("#issueField").blur(function(){
if($("#issueField").val()==''){
        $("#issueTick").css("opacity", "0");
}
    });  
});

Upvotes: 0

hardkoded
hardkoded

Reputation: 21627

Though I think there are better ways to implement this, for instance, I don't know why you are using the opacity instead of display none/block. this should work for you:

$(document).ready(function(){
    $("#issueField").keyup(function(){
            if($("#issueField").val()) {
            $("#issueTick").css("opacity", "1");
        } else { 
             $("#issueTick").css("opacity", "0");
        }
    });    
});

Notice that I'm using keyup, because we need to intercept the key after the value has changed.

Upvotes: 3

Related Questions