Ali Farooq Ali Farooq - 2 months ago 12
HTML Question

How to display text in a span tag based on the value of input field

I want to display text "USERNAME" in the span tag based on the value of input field.

If input field has any value I want to display the text "USERNAME" in the span tag. If input field has no value then I want the span tag to have no text inside it.



$(function () {
$("#username-input")
.keydown(function () {
function addRemoveUsername() {
var inputChecker = document.getElementById("username-input");
if (inputChecker.value == "") {
document.getElementById("name")
.innerHTML = "";
} else {
document.getElementById("name")
.innerHTML = "USERNAME";
}
}
addRemoveUsername();
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="login-form">
<span id="name"></span><br>
<input id="username-input" type="text" placeholder="USERNAME">
</form>





Just how do I do it?

Answer

Use .keyup as below snippet.

$(function () {
  $("#username-input").keyup(function() {
    var inputChecker = document.getElementById("username-input");
    //blank spaces will be trimmed before text from the input field
    if ($.trim(inputChecker.value) == "") {
      document.getElementById("name").innerHTML = ""; 
      inputChecker.value = "";
    } else {
      document.getElementById("name").innerHTML = "USERNAME";
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id ="login-form">
    <span id="name"></span><br>
    <input id="username-input" type="text" placeholder="USERNAME">
</form>