본문 바로가기

Programming/JavaScript/AJAX

[JavaScript] this.form 사용하기

이게 생각처럼 되는게 아니라 어떨때는 되고 어떨때는 안되길래
왜 그럴까 하루 종일 고민해 본 결과를 정리한다.

예를 들어 아래와 같은 소스를 보자.

<html>
 <head>
  <title> New Document </title>
  <script language="JavaScript">
  <!--
	function test(this_form)
	{	//아래의 호출한 이벤트핸들러를 통해 폼의 이름을 그대로 받아서 쓰게되죠.
		alert(this_form.text_field.value);
	}
  //-->
  </script>
 </head>

 <body>
  <form name="test_form" method="post" action="">
  <input type="text" name="text_field">
  <input type="button" _onclick="test(this.form)" value="alert">
  <!-- 위 버튼을 누르면 이벤트 핸들러를 통해 document.test_form 이라는 object 를 함수로 보냅니다 -->
  </form>
 </body>
</html>

이 소스에서는 this.form(form name으로 선언된 이름) 이 정상적으로 동작한다.

하지만 아래 소스에서는 동작하지 않는다.

<html>
 <head>
  <title> New Document </title>
  <script language="JavaScript">
  <!--
	function test(this_form)
	{	
		alert(this_form.text_field.value);
	}
  //-->
  </script>
 </head>

 <body>
  <form name="test_form" method="post" action="">
  <input type="text" name="text_field">
  <a href="javascript:test(this.form);">
    <input type="text" name="test_btn" value="alert">
  </a>
  </form>

무슨 차이가 있을까?

하나는 input tag에서 this.form 을 호출했고, 다른 하나는 a tag에서 호출했다.

input에서 부를때는 되지만, a 에서 부르면 안된다는 말이다.

이유를 정확히는 모르겠지만 a tag는 현재 form에 포함되지 않는 객체라서 그런 것 같다. (정확히는 모르겠지만 저렇게 쓰면 안된다는것은 확신한다.)