If the two textbox values ​​are not empty then execute the function

Fiddle: http://liveweave.com/TBJ9EZ

I have two text boxes input[type=text] elements

and I want to do this as soon as they have a value of "not empty". I want to show the div, and as soon as each one has an empty value to hide the div.

What am I doing wrong?

$(document).ready(function() {
  var AppName = $(".appname").val(),
      AppUrl = $(".appurl").val();

  $("input").on("keyup change", function() {
    if ((AppName === "") && (AppUrl === "")) {
      $("div").addClass("hide");
    } else {
      $("div").removeClass("hide");
    }
  });
});
      

.hide {
  display: none;
}
      

<!DOCTYPE html>
<html>
  <head>
    <title>Check Fields</title>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=9" />
    <link type="text/css" rel="stylesheet" href="http://necolas.github.io/normalize.css/3.0.1/normalize.css" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
  </head>
  <body>
    <input class="appname" type="text" placeholder="Application name"> 
    <input class="appurl" type="text" placeholder="http://website.com/">
    <div class="hide">All fields are filled :)</div>
  </body>
</html>
      

Run codeHide result


+3


source to share


1 answer


You have to use the move operator to retrieve the value inside the click handler.

$("input").on("keyup change", function() {
  var AppName = $(".appname").val(),
      AppUrl = $(".appurl").val();

    if ((AppName === "") && (AppUrl === "")) {
      $("div").addClass("hide");
    } else {
      $("div").removeClass("hide");
    }
});

      

You can also use .toggleClass(state)



A boolean value to determine whether to add or remove a class.

$("input").on("keyup change", function() {
    $("div").toggleClass("hide", $(".appname").val() === "" && $(".appurl").val() === "");
});

      

+6


source







All Articles