skip to Main Content

My goal is to create a text for a username where a user would enter text but if the words are less than five letters, then the paragraph underneath would alert them that their username is less than five letters, i am using an event handler to go about this, something which i am still learning to workaround, so i would like to know what I am doing wrong. I also added fallback codes for older browsers.

<form>
  <input type="text" id="text1"
  /><p id="response"></p>
</form>

function input(e, minlength) {
  var target1 = e.target || e.srcElement; //element which the event is working on
  var paragraph1 = target.nextSibling;

  if (!e) {
    e = window.event;
  }
  
  
  if (target1.value.length < minlength) {
    paragraph1.textContent =
      "Your username should be" + minlength + "letters and above";
  }
}

var input1 = document.getElementById("text1");
if (input1.addEventListener) {
  input1.addEventListener(
    "blur",
    function (e) {
      input(e, 5);
    },
    false
  );
}

else{
  input1.attachEvent(
    "onblur",
    function (e) {
      input(e, 5);
    },
    false
  );
}

2

Answers


  1. This code should do it! It’s nothing fancy, but you can build on it pretty easily.

    // Select the input and paragraph elements
    const inputElement = document.getElementById('text1');
    const paragraphElement = document.getElementById('response');
    
    // Add an event listener to the input element
    inputElement.addEventListener('input', function() {
      // Get the value of the input
      const inputValue = inputElement.value;
    
      // Check the length of the input value
      if (inputValue.length < 5) {
        paragraphElement.textContent = 'Input is less than 5 characters';
      } else {
        paragraphElement.textContent = 'Input is 5 characters or more';
      }
    });
    <form>
      <input type="text" id="text1"
      /><p id="response"></p>
    </form>
    Login or Signup to reply.
  2. you should correct this line because of this line paragraph1 is not get properly you should use nextElementSibling to get paragraph1

     var paragraph1 = target.nextSibling; 
    

    you should correct above line to

    var paragraph1 = target1.nextElementSibling;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search