wrkbrs
[jQuery] How to Reset a Form with jQuery 본문
Clearing a form is something that you often need to do on a website, for example if you want to empty the form fields after submitting a form with Ajax.
Resetting a form using JavaScript is pretty straightforward, you can just call:
document.getElementById("#myform").reset();
But calling the reset()
function on a jQuery object will not work. You’ll get an error saying TypeError: $(...).reset is not a function
.
Why is that?
Well, the reset()
function is a regular JavaScript function, not a jQuery function, and therefore won’t work on a jQuery object.
To get it to work, we need to extract the underlying DOM element from the jQuery object, and then we can call the function.
A jQuery object contains one or more DOM elements, and you can access the elements in it with normal array syntax, so this will work:
$("#myform")[0].reset();
Another way is to trigger the reset event by calling
$("#myform").trigger('reset');
Note that these methods will only reset the form fields to their initial values. It will not empty fields that has default values set on them.
https://magnusbenoni.com/reset-form-jquery/
'jQuery' 카테고리의 다른 글
[jQuery] UI autocomplete(입력필드 자동완성) 사용하기 (0) | 2019.07.30 |
---|---|
<button type=button> type 속성 유무 차이 (0) | 2019.01.18 |
test태그에서 하위 태그 제외하고 가져오기. (0) | 2019.01.18 |
[jQuery] 자식제외 클래스의 텍스트 선택하기 (0) | 2019.01.18 |
[jQuery] API 정복 - attr(), 속성을 제어하기 (0) | 2019.01.14 |