How to remove css if input field is empty

I am creating a button showing that there is content in the input field which works great. However, if I delete all the content, it remains because I am not sure how to change the process to some sort of switch. This is where I am with him at the moment:

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

      

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

+3


source to share


4 answers


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

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

      



Note that I am using keyup because we need to intercept the key after the value has changed.

+3


source


You can use +!!$(this).val()

CSS for opacity value. It will be 0 or 1 depending on whether there is text content in your input.

I also suggest listening for the event input

instead of the event keyup

, as the first one will also be triggered by other ways of changing 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>
      

Run codeHide result


+6


source


Try

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

      

+1


source


you need to set a blur event to check if the textbox value is empty so that it returns the opacity to 0 after blurring from it.

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

      

0


source







All Articles