jQuery / input 값 변화 감지하기 / change, keyup

input 요소에 값을 입력하거나 선택했을 때, 이를 감지하여 어떤 작업을 할 수 있다. input의 type이 number일 때, checkbox일 때, radio일 때로 나누어서 어떻게 감지하는지 알아본다.

input type="number"

숫자를 입력할 수 있는 폼 두 개를 만들고, 값을 입력했을 때 두 수의 곱을 출력해보자.

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>jQuery</title>
    <style>
      * {
        font-family: Consolas;
      }
    </style>
  </head>
  <body>
    <p>A <input type="number" id="a"></p>
    <p>B <input type="number" id="b"></p>
    <p>A * C = <span id="ab"></span></p>
  </body>
</html>

change()로 감지하기

change()는 값을 입력하고 해당 폼을 벗어났을 때 변화를 감지한다.

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>jQuery</title>
    <script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
    <script>
      $( document ).ready( function() {
        $( '#a, #b' ).change( function() {
          var a = $( '#a' ).val();
          var b = $( '#b' ).val();
          var ab = a * b;
          $( '#ab' ).text( ab );
        } );
      } );
    </script>
    <style>
      * {
        font-family: Consolas;
      }
    </style>
  </head>
  <body>
    <p>A <input type="number" id="a"></p>
    <p>B <input type="number" id="b"></p>
    <p>A * C = <span id="ab"></span></p>
  </body>
</html>

2를 입력하는 순간에는 아무 일이 없지만...

폼을 벗어나면 2와 0의 곱 0을 출력한다.

마찬가지로, 두 번째 폼에 3을 입력하는 순간에는 아무 일이 없지만...

폼을 벗어나면 2와 3의 곱 6을 출력한다.

keyup()으로 감지하기

change() 대신 keyup()을 사용하면 입력하는 순간 변화를 감지한다.

<script>
  $( document ).ready( function() {
    $( '#a, #b' ).keyup( function() {
      var a = $( '#a' ).val();
      var b = $( '#b' ).val();
      var ab = a * b;
      $( '#ab' ).text( ab );
    } );
  } );
</script>

on()

on()을 사용하여 여러 이벤트에 대해서 같은 작업을 할 수 있다. 다음은 폼을 선택했을 때도 계산한다.

<script>
  $( document ).ready( function() {
    $( '#a, #b' ).on( 'focus keyup', function() {
      var a = $( '#a' ).val();
      var b = $( '#b' ).val();
      var ab = a * b;
      $( '#ab' ).text( ab );
    } );
  } );
</script>

input type="checkbox"

체크박스에 체크하면 Checked를 출력하고, 체크를 지우면 아무 것도 표시하지 않는다.

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>jQuery</title>
    <script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
    <script>
      $( document ).ready( function() {
        $( '#a' ).change( function() {
          if ( $( '#a' ).is( ':checked' ) ) {
            $( '#b' ).text( 'Checked' );
          } else {
            $( '#b' ).text( '' );
          }
        } );
      } );
    </script>
    <style>
      * {
        font-family: Consolas;
      }
    </style>
  </head>
  <body>
    <p>A <input type="checkbox" id="a"></p>
    <p id="b"></p>
  </body>
</html>

on()을 사용해도 된다.

<script>
  $( document ).ready( function() {
    $( '#a' ).on( 'change', function() {
      if ( $( '#a' ).is( ':checked' ) ) {
        $( '#b' ).text( 'Checked' );
      } else {
        $( '#b' ).text( '' );
      }
    } );
  } );
</script>

input type="radio"

라디오 버튼을 클릭하면, 그 버튼에 해당하는 값이 출력된다.

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>jQuery</title>
    <script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
    <script>
      $( document ).ready( function() {
        $( 'input[name="fruit"]' ).change( function() {
          $( '#a' ).text( $( this ).val() );
        } );
      } );
    </script>
    <style>
      * {
        font-family: Consolas;
      }
    </style>
  </head>
  <body>
    <p><input type="radio" name="fruit" value="Apple"> Apple</p>
    <p><input type="radio" name="fruit" value="Banana"> Banana</p>
    <p id="a"></p>
  </body>
</html>

on()을 사용해도 된다.

<script>
  $( document ).ready( function() {
    $( 'input[name="fruit"]' ).on( 'change', function() {
      $( '#a' ).text( $( this ).val() );
    } );
  } );
</script>
같은 카테고리의 다른 글
jQuery / Method / .animate() - 애니메이션 효과 만드는 메서드

jQuery / Method / .animate() - 애니메이션 효과 만드는 메서드

.animate .animate()는 애니메이션 효과를 만듭니다. 문법 .animate( properties ) properties 애니메이션 효과를 줄 속성을 정합니다. 가능한 속성은 다음과 같습니다. backgroundPositionX backgroundPositionY borderBottomWidth borderLeftWidth borderRightWidth borderSpacing borderTopWidth borderWidth bottom fontSize height left letterSpacing lineHeight margin marginBottom marginLeft marginRight marginTop maxHeight maxWidth minHeight minWidth opacity outlineWidth padding paddingBottom paddingLeft paddingRight paddingTop right textIndent top width wordSpacing duration 애니메이션 효과를 완료할 때까지 걸리는 시간입니다. 단위는 1/1000초, 기본값은 400입니다. fast나 slow로 정할 수 있습니다. fast는 200, slow는 600에 해당합니다. easing 애니메이션 효과의 방식을 정합니다. swing과 linear이 가능하며, 기본값은 swing입니다. complete 요소가 사라진 후 ...

jQuery / Method / .replaceWith() - 선택한 요소를 다른 것으로 바꾸는 메서드

jQuery / Method / .replaceWith() - 선택한 요소를 다른 것으로 바꾸는 메서드

.replaceWith() .replaceWith()는 선택한 요소를 다른 것으로 바꿉니다. 문법 .replaceWith( newContent ) 예를 들어 h1 요소를 abc로 바꾸고 싶다면 다음과 같이 합니다. $( 'h1' ).replaceWith( 'abc' ); h1 요소의 내용 뿐 아니라 h1 태그까지 지우고 바꾼다는 것에 주의합니다. newContent에는 특정 요소가 들어갈 수 있습니다. 예를 들어 $( 'h1' ).replaceWith( $( 'p.a' ) ); 는 h1 요소를 클래스 값이 a인 p ...

jQuery / Method / .text() - 선택한 요소 안의 내용을 가져오거나, 다른 내용으로 바꾸는 메서드

jQuery / Method / .text() - 선택한 요소 안의 내용을 가져오거나, 다른 내용으로 바꾸는 메서드

.text() .text()는 선택한 요소 안의 내용을 가져오거나, 다른 내용으로 바꿉니다. .html()과 비슷하지만 태그의 처리가 다릅니다. 문법 1 .text() 선택한 요소 안의 내용을 가져옵니다. 태그는 가져오지 않습니다. 예를 들어 var jb = $( 'h1' ).text(); 는 h1 요소의 내용을 변수 jb에 저장합니다. 문법 2 .text( textString ) 이전 내용을 지우고 새로운 내용을 넣습니다. 예를 들어 $( 'div' ).html( '<h1>Lorem</h1>' ); 는 div ...

jQuery / Plugin / jquery.toc / H 태그로 목차 만드는 플러그인

jQuery / Plugin / jquery.toc / H 태그로 목차 만드는 플러그인

jquery.toc jquery.toc는 HTML 문서에 있는 h1, h2 등 h 태그를 이용하여 자동으로 목차를 만들어주는 플러그인입니다. GitHub : https://github.com/ndabas/toc Download : http://ndabas.github.com/toc/assets/jquery.toc.zip 목차 클릭 시 부드럽게 이동하는 효과를 주고 싶다면 다른 플러그인을 사용하세요. 기본 사용법 h 태그가 많은 다음과 같은 HTML 문서를 만듭니다. <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>jQuery</title> <style> body { font-family: Consolas, sans-serif; } a { color: blue; } </style> </head> <body> <h1>Lorem</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing ...

jQuery / Method / .removeClass() - 선택한 요소의 클래스 값을 제거하는 메서드

jQuery / Method / .removeClass() - 선택한 요소의 클래스 값을 제거하는 메서드

.removeClass() .removeClass()로 선택한 요소에서 클래스 값을 제거할 수 있습니다. 문법 .removeClass( className ) 클래스 값은 큰 따옴표 또는 작은 따옴표로 감쌉니다. $( 'h1' ).removeClass( 'abc' ); 띄어쓰기로 구분하여 여러 개의 값을 제거할 수 있습니다. $( 'h1' ).removeClass( 'ab cd ef' ); 페이지가 로드된 상태에서 클래스 값이 제거되는 것이므로, 제거되기 전의 모양에서 제거된 후의 모양으로 변하는 것을 방문자가 볼 ...

jQuery / jQuery.noConflict() / 다른 라이브러리, 다른 버전의 jQuery와 충돌 방지하기

jQuery / jQuery.noConflict() / 다른 라이브러리, 다른 버전의 jQuery와 충돌 방지하기

jQuery를 사용할 때 다른 라이브러리와 충돌이 나는 경우가 있습니다. 충돌의 원인은 두 가지로 구분할 수 있습니다. 다른 라이브러리와 충돌 다른 버전의 jQuery와 충돌 각 경우에 대해서 어떻게 충돌을 방지할 수 있는지 알아보겠습니다. 다른 라이브러리와 충돌 jQuery는 $를 jQuery의 alias로 사용합니다. 그런데 다른 라이브러리에서 $를 함수나 변수로 사용한다면 jQuery가 제대로 작동하지 않을 수 있습니다. 이를 방지하는 방법은 ...

jQuery / Method / .has() - 특정 요소를 가지고 있는 요소를 선택하는 메서드

jQuery / Method / .has() - 특정 요소를 가지고 있는 요소를 선택하는 메서드

.has() .has()로 특정 요소를 가지고 있는 요소를 선택할 수 있습니다. 문법 .has( selector ) 예를 들어 $( 'h1' ).has( 'span' ) 은 span 요소를 가지고 있는 h1 요소를 를 선택합니다. 예제 span 요소를 포함하고 있는 h1 요소의 글자색을 빨간색으로 만듭니다. <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>jQuery</title> <script src="//code.jquery.com/jquery-3.3.1.min.js"></script> ...

jQuery / Method / .slice() - 일치하는 요소의 일부분만 선택하는 메서드

jQuery / Method / .slice() - 일치하는 요소의 일부분만 선택하는 메서드

.slice() .slice()는 일치하는 요소의 일부분만 선택합니다. 문법 .slice( start ) 예를 들어 $( 'li' ).slice( 2 ).css( 'color', 'red' ); 는 li 요소 중 3번째부터 빨간색으로 만듭니다. $( 'li' ).slice( 2, 5 ).css( 'color', 'red' ); 는 li 요소 중 3번째부터 5번째까지 빨간색으로 만듭니다. $( 'li' ).slice( -4, -2 ).css( 'color', 'red' ); 는 li 요소 중 ...

jQuery / Selector / :selected - select에서 선택된 option를 선택하는 선택자

jQuery / Selector / :selected - select에서 선택된 option를 선택하는 선택자

:selected는 select에서 선택된 option를 선택한다. :selected 대신 :checked를 사용해도 된다. 색을 선택하면 그 값을 div 요소의 배경색으로 만든다. <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>jQuery</title> <style> * { font-family: Consolas, monospace; ...

jQuery / Method / .get() - 선택한 요소를 배열로 가져오는 메서드

jQuery / Method / .get() - 선택한 요소를 배열로 가져오는 메서드

.get() .get()은 선택한 요소를 배열(Array)로 가져옵니다. 문법 .get() 선택한 모든 요소를 가져옵니다. .get( index ) 선택한 요소 중 특정한 것만 가져옵니다. 예제 1 모든 li 요소를 jb 배열로 가져온 후, 각 요소의 내용을 출력합니다. <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>jQuery</title> <script src="//code.jquery.com/jquery-3.3.1.min.js"></script> <script> ...