3

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?

1
  • I think I may have misunderstood what you wanted. What value did the input text have before the ajax, and what does it have afterwards? Commented Aug 15, 2019 at 12:05

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

It only works with forms whereas I want to apply it to input
@DeadUnicorn you are right, I edited the answer, check if it's working for you
It has the same effect as $(selector).val(""). Field becomes invalid after it
@DeadUnicorn read about the form within a form solution I suggested
1
$(document).ready(function () {
   $("#input-id").val("");
   //If you also want to set innerText:
   var ele = document.getElementById('input-id');
   ele.innerText= $("#input-id").val();
};

As soon as the document is ready (the page is loaded) then the input becomes invalid. Place this wherever you think is appropriate.

3 Comments

The problem is to make it valid after $("#input-id").val("") (without putting text inside of it)
@DeadUnicorn Just to clarify, did you care only about val() or also about innerText?
@DeadUnicorn added an innerText thing too if that's what you wanted?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.