Search code examples
javascripthtmlcssfrontendrequired

How to make input valid with js?


I have a required input :

<input type="text" id="input-id" required>

When user submit it I send its value with ajax and then clear it with $("#input-id").val("").
After it input becomes invalid, but I want to make it looks like it did right after page loading. How can I do it with js? Maybe I should clear input in another way?


Solution

  • Try to do what's written here:

    document.getElementById(selector).reset();
    

    if you want to reset a particular field, try use defaultValue:

    function reset() {
      field = document.getElementById('field');
      field.value = field.defaultValue;
    }
    <input id="field" type="text" required>
    <button onclick="reset()">reset field</button>

    Another solution will be to define a form within a form, that contains only the fields you want to reset, and then reset the inner form.