Home » Jquery » javascript – JQuery Toggle InputBox based on if another Inputbox has value-Exceptionshub

javascript – JQuery Toggle InputBox based on if another Inputbox has value-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have a page that contains two input boxes. I need one input box to disappear and then reappear depending on if there is a value in the other one. I’ve read that using JQuery is the easiest way to do this however I have limited experience with it and can’t find documentation on how to implement this. Here is the page:

<label asp-for="Subject" class="control-label"></label>
<input asp-for="Subject" class="form-control" id="Subject"/>

<label asp-for="Header" class="control-label"></label>
<input asp-for="Header" class="form-control" id="Header"/>

Here is the JQuery I have so far from my limited knowledge. The input box is gone at the start.

<script type="text/javascript">
$("#Subject").val(function () {
    $("#Header").toggle(this.length > 0);
});

I am not sure how to implement this where writing text in one textbox will make the other one disappear. The debugger is not supplying any error messages about the code.

How to&Answer:

If you want to show the “Header” when the user has typed something in the “Subject”-input:

$("#Subject").on("input", function () {
   $("#Header").toggle(!!$(this).val().length);
});

You should also add style="display: none;" to the header to initially hide it.

Alternatively you could trigger the ‘input’ event manually once:

$("#Subject").on("input", function () {
   $("#Header").toggle(!!$(this).val().length);
}).trigger("input");

Answer:

$("#Subject").on("input", function() {
  let $e = $("#Header");
  $(this).val() == "" ? $e.addClass("hidden"): $e.removeClass("hidden");
});
.hidden {
  display: none !important; 
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
  <label asp-for="Subject" class="control-label"></label>
  <input asp-for="Subject" class="form-control" id="Subject"/>

  <label asp-for="Header" class="control-label"></label>
  <input asp-for="Header" class="form-control hidden" id="Header"/>
</body>

</html>