Ad

JQuery Toggle InputBox Based On If Another Inputbox Has Value

- 1 answer

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.

Ad

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");
Ad
source: stackoverflow.com
Ad