JavaScript / Event / onsubmit / 폼 전송하기 전에 작업 수행하게 하는 이벤트

JavaScript의 onsubmit 이벤트를 이용하면 폼의 값을 전송하기 전에 어떤 작업을 하게 할 수 있습니다. 간단한 예제로 어떻게 작동하는지 알아보겠습니다.

예제 1

  • 간단한 회원 가입 페이지를 만듭니다. 전송 버튼은 input 태그로 만듭니다.
  • Register를 클릭하면 ok.html로 이동합니다.
<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>JavaScript</title>
    <style>
      input, button { font-family: inherit; font-size: inherit; }
    </style>
  </head>
  <body>
    <h1>Register</h1>
    <form action="ok.html" method="POST">
      <p><input type="text" name="username" placeholder="Username" required></p>
      <p><input type="password" name="password" placeholder="Password" required id="pw1"></p>
      <p><input type="password" name="password-confirm" placeholder="Confirm Password" required id="pw2"></p>
      <p><input type="submit" value="Register"></p>
    </form>
  </body>
</html>

  • form 태그에 onsubmit="jbSubmit();"를 추가합니다. 전송 버튼을 클릭하면 jbSubmit() 함수를 호출하라는 뜻입니다.
<form action="ok.html" method="POST" onsubmit="jbSubmit();">
  • jbSubmit()은 비밀번호 두 개를 받아서 알려주는 함수입니다.
<script>
  function jbSubmit() {
    var pw1 = document.getElementById( 'pw1' ).value;
    var pw2 = document.getElementById( 'pw2' ).value;
    alert( pw1 + ' vs ' + pw2 );
  }
</script>
  • 전체 코드는 다음과 같습니다.
<!doctype html>
<html lang="ko">
  <head>
  <meta charset="utf-8">
  <title>JavaScript</title>
    <style>
      input, button { font-family: inherit; font-size: inherit; }
    </style>
    <script>
      function jbSubmit() {
        var pw1 = document.getElementById( 'pw1' ).value;
        var pw2 = document.getElementById( 'pw2' ).value;
        alert( pw1 + ' vs ' + pw2 );
      }
    </script>
  </head>
  <body>
    <h1>Register</h1>
    <form action="ok.html" method="POST" onsubmit="jbSubmit();">
      <p><input type="text" name="username" placeholder="Username" required></p>
      <p><input type="password" name="password" placeholder="Password" required id="pw1"></p>
      <p><input type="password" name="password-confirm" placeholder="Confirm Password" required id="pw2"></p>
      <p><input type="submit" value="Register"></p>
    </form>
  </body>
</html>
  • 이제 폼에 정보를 입력하고 Register를 클릭하면 두 개의 비밀번호를 알려주고, [확인]을 클릭하면 ok.html로 이동합니다.

예제 2

  • jbSubmit() 앞에 return을 추가합니다.
<form action="ok.html" method="POST" onsubmit="return jbSubmit();">
  • 두 개의 비밀번호를 비교해서 값이 다르면 false를, 같으면 true를 반환합니다.
<script>
  function jbSubmit() {
    var pw1 = document.getElementById( 'pw1' ).value;
    var pw2 = document.getElementById( 'pw2' ).value;
    if ( pw1 != pw2 ) {
      alert( 'Confirm Password!' );
      return false;
    }
  }
</script>
  • 전체 코드는 다음과 같습니다.
<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>JavaScript</title>
    <style>
      input, button { font-family: inherit; font-size: inherit; }
    </style>
    <script>
      function jbSubmit() {
        var pw1 = document.getElementById( 'pw1' ).value;
        var pw2 = document.getElementById( 'pw2' ).value;
        if ( pw1 != pw2 ) {
          alert( 'Confirm Password!' );
          return false;
        }
      }
    </script>
  </head>
  <body>
    <h1>Register</h1>
    <form action="ok.html" method="POST" onsubmit="return jbSubmit();">
      <p><input type="text" name="username" placeholder="Username" required></p>
      <p><input type="password" name="password" placeholder="Password" required id="pw1"></p>
      <p><input type="password" name="password-confirm" placeholder="Confirm Password" required id="pw2"></p>
      <p><input type="submit" value="Register"></p>
    </form>
  </body>
</html>
  • 값을 입력하고 전송할 때, 두 개의 비밀번호가 같다면 ok.html로 이동합니다.
  • 값이 다르다면 아래와 같이 메시지를 띄우고, [확인]을 클릭하면 현재 페이지에 머뭅니다.

Related Posts

JavaScript / Object / String.endsWith() / 특정 문자열로 끝나는지 확인하는 메서드

JavaScript / Object / String.endsWith() / 특정 문자열로 끝나는지 확인하는 메서드

.endsWith() .endsWith()는 문자열이 특정 문자열로 끝나는지 확인한다. IE는 Edge부터 지원한다. 문법 string.endsWith( searchString, length ) searchString : 검색할 문자열로 필수 요소이다. 대소문자를 구분한다. length : 문자열 중 어디까지 검색할지 정한다. 선택 요소로, 값이 없으면 전체 문자열을 대상으로 한다. 예제 abcde가 e로 끝나는지 검사한다. e로 끝나므로 true를 반환한다. 'abcde'.endsWith( 'e' ) abc가 e로 끝나는지 검사한다. e로 끝나지 않으므로 false를 반환한다. 'abcde'.endsWith( ...

JavaScript / Object / Screen / 화면 정보 가져오는 객체

JavaScript / Object / Screen / 화면 정보 가져오는 객체

Screen Screen은 화면 정보를 가져오는 객체입니다. 속성은 다음과 같습니다. screen.width 화면의 가로 크기를 가져옵니다. screen.height 화면의 세로 크기를 가져옵니다. screen.availWidth 작업 표시줄이 차지하는 부분을 제외한 가로 크기를 가져옵니다. screen.availHeight 작업 표시줄이 차지하는 부분을 제외한 세로 크기를 가져옵니다. screen.colorDepth screen.pixelDepth IE는 버전 10 이상에서 사용할 수 있습니다. 예제 <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>JavaScript</title> <style> body { font-family: Consolas, monospace; } </style> ...

JavaScript / Object / String.includes() / 특정 문자열을 포함하는지 확인하는 메서드

JavaScript / Object / String.includes() / 특정 문자열을 포함하는지 확인하는 메서드

.includes() .includes()는 문자열이 특정 문자열을 포함하는지 확인하는 메서드이다. IE는 Edge부터 지원한다. 문법 string.includes( searchString, length ) searchString : 검색할 문자열로 필수 요소이다. 대소문자를 구분한다. length : 검색을 시작할 위치이다. 선택 요소로, 값이 없으면 전체 문자열을 대상으로 한다. 예제 abzcd가 z를 포함하는지 검사한다. z를 포함하므로 true를 반환한다. 'abzcd'.includes( 'z' ) zcd가 z를 포함하는지 검사한다. z를 포함하므로 true를 반환한다. 'abzcd'.includes( 'z', 2 ...

JavaScript / Object / Date

JavaScript / Object / Date

현재 날짜와 시간 가져오기 Date()로 현재 날짜와 시간을 가져온다. <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>JavaScript</title> <style> body { font-family: Consolas, monospace; font-size: ...

JavaScript / Object / Math.log(), Math.log10(), Math.Log2()

JavaScript / Object / Math.log(), Math.log10(), Math.Log2()

Math.log(), Math.log10(), Math.Log2() Math.log() : 자연로그의 값을 반환합니다. Math.log10() : 상용로그의 값을 반환합니다. Math.Log2() : 밑이 2인 로그의 값을 반환합니다. 문법 Math.log( number) Math.log10( number ) Math.Log2( number) number에는 숫자가 들어갑니다. 0인 경우 -Infinity, 음수인 경우 NaN을 반환합니다. 예제 <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>JavaScript</title> <style> ...

JavaScript / Object / Date / 당월 말일 구하는 방법

JavaScript / Object / Date / 당월 말일 구하는 방법

다음은 2022년 3월 1일이다. Date( 2022, 2, 1 ) 날짜 자리에 0이 들어가면 전달 말일이다. 즉 다음은 2022년 2월 28일이다. Date( 2022, 2, 0 ) 이를 이용하여 현재 달의 말일을 구할 수 있다. 다음은 오늘 날짜를 출력하는 것이고... <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>JavaScript</title> ...

JavaScript / Object / String.substr() / 문자열 추출하는 메서드

JavaScript / Object / String.substr() / 문자열 추출하는 메서드

.substr() .substr()은 문자열에서 특정 부분만 골라낼 때 사용하는 메서드입니다. 문법 string.substr( start, length ) start로 시작 위치를 정하고 length로 잘라낼 문자열의 길이를 정합니다. 예를 들어 var str = '123456789'; document.write( '<p>substring( 1, 5 ) : ' + str.substr( 1, 5 ) + '</p>' ); 는 23456을 출력합니다. start 값은 필수이고, length를 지정하지 않으면 문자열의 끝까지를 가져옵니다. 예제 <!doctype html> <html lang="ko"> ...

JavaScript / 메모

JavaScript / 메모

인코딩 함수, 디코딩 함수 인코딩 함수 escape() encodeURI() encodeURIComponent() 디코딩 함수 unescape() decodeURI() decodeURIComponent() IE8에서 last-child, nth-child 등 가상 클래스 적용시키는 방법 selectivizr HTML 문서의 style 태그 안에 넣은 CSS 코드에는 적용되지 않는다. 외부 CSS 파일에만 적용됩니다. jQuery, prototype 등 다른 자바스크립트 라이브러리가 필요하다.

JavaScript / Object / Array.length / 배열의 길이 반환하는 속성

JavaScript / Object / Array.length / 배열의 길이 반환하는 속성

.length .length는 배열의 길이를 반환하는 속성입니다. 마지막 원소의 인덱스 값보다 1 큰 수를 반환합니다. 배열에 속한 원소의 개수와는 의미가 다릅니다. 문법 array.length 예제 <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>JavaScript</title> <style> body { font-family: Consolas, sans-serif; font-style: italic; } </style> </head> <body> <script> var jbAry1 = ; document.write( '<p>jbAry1.length : ' ...

JavaScript / Object / String.startsWith() / 특정 문자열로 시작하는지 확인하는 메서드

JavaScript / Object / String.startsWith() / 특정 문자열로 시작하는지 확인하는 메서드

.startsWith() .startsWith()는 문자열이 특정 문자열로 시작하는지 확인한다, IE는 Edge부터 지원한다. 문법 string.startsWith( searchString, length ) searchString : 검색할 문자열로 필수 요소이다. 대소문자를 구분한다. length : 문자열 중 어디까지 검색할지 정한다. 선택 요소로, 값이 없으면 전체 문자열을 대상으로 한다. 예제 abcde가 a로 시작하는지 검사한다. a로 시작하므로 true를 반환한다. 'abcde'.startsWith( 'a' ) bcde가 a로 시작하는지 검사한다. a로 시작하지 않으므로 false를 반환한다. 'abcde'.startsWith( ...