skip to Main Content

Example:

When the user is filling the field, I want that the user should not be able to clear or delete the value i.e "Friend". Is it possible to achieve this using CSS or JavaScript?

2

Answers


  1. Is it possible? Sure. Anything is possible.

    input.addEventListener("focusout", () => { 
        input.setAttribute("disabled", "");
    });
    

    But you should make sure that you’re not adversely affecting accessibility or usability.

    I think that the disabled attribute is more appropriate than readonly, as it also conveys some semantics and comes with the benefit of default styling in most browsers.

    Login or Signup to reply.
  2. You can add an event listener to the input element "onInput" and pass the bellow function to it, like this…

    const inputElement = document.querySelector('input');
    let previousElement = "";
    function X (e){
      
      if(e.target.value.length >  previousElement.length){
        previousElement = e.target.value;
        return;
      }else{
        e.target.value = previousElement;
      }
    }
    inputElement.addEventListener('input', X);
    

    This function stores the last input value until the user adds letters, i.e. until the last input’s value’s length is greater than the current one. But if the user tried to delete letters i.e. current input’s value’s length is less than the previous input value then this function will replace the current deleted value with the previous value.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search