How to hide element based on input value with javascript?

I'm trying to hide/show input and div based on Input value.

The code below isn't working:

HTML:

<div>
     <span class='just-show'>Show This Label</span>
     <input class='for-input' type='text' value='*$set-by-sql-data*'>
</div>

JS

$(document).ready(function () {
    if ($(".for-input").val()=='') {
        $(".just-show").show();
        $(".for-input").hide();
    } else {
        $(".just-show").hide();
        $(".for-input").show();
    }
    return false;
});

How to hide the element without event (ex: click) ? Just on ready function.

Answers 1

  • You can use

    $(document).on('change', 'input', function() {
      // Does some stuff and logs the event to the console
    });
    

    Or

    $("input").change(function(){
        // Does some stuff and logs the event to the console
    });
    

    Where input is Input identifier like your .for-input

    Your desire Jquery code:

    $(document).on('change', '.for-input', function() {
        if ($(".for-input").val()=='') {
            $(".just-show").show();
            $(".for-input").hide();
        } else {
            $(".just-show").hide();
            $(".for-input").show();
        }
    });
    

    Example:

    $(document).ready(function () {
        if ($(".for-input").val()=='') {
            $(".just-show").show();
            $(".for-input").hide();
        } else {
            $(".just-show").hide();
            $(".for-input").show();
        }
        //return false;
      
      $(document).on('change', '.for-input', function() {
         if ($(".for-input").val()=='') {
            $(".just-show").show();
            $(".for-input").hide();
        } else {
            $(".just-show").hide();
            $(".for-input").show();
        }
      });
      
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <div>
         <span class='just-show'>Show This Label</span>
         <input class='for-input' type='text' value='*$set-by-sql-data*'>
    </div>


Related Articles