Programming/JavaScript

[JavaScript] javascript 상에서 form.reset()(or Button type="reset")

OriginMaster 2022. 2. 8. 21:18
반응형
  • 필요성
  1. HTML 상에서 <button type="reset" onclick="function();"> 의 동작을 처리할 때, onClick을 실행 후 reset을 처리해주기 때문에, reset이 적용되지 않은 상태의 이벤트가 발생된다.
  2. Javascript 의 form 의 reset() 메소드는 hidden field 와 check, radio button 에 대해 초기화를 시켜주지 않는다. 따라서 form 의 모든 field 를 초기화 시키려면 아래의 메소드가 필요하다.

 

$.fn.clearForm = function () {
  return this.each(function () {
    var type = this.type,
      tag = this.tagName.toLowerCase();
    if (tag === 'form') {
      return $(':input', this).clearForm();
    }
    if (
      type === 'text' ||
      type === 'password' ||
      type === 'hidden' ||
      tag === 'textarea'
    ) {
      this.value = '';
    } else if (type === 'checkbox' || type === 'radio') {
      this.checked = false;
    } else if (tag === 'select') {
      this.selectedIndex = -1;
    }
  });
};
반응형