HOWTO · jQuery

jQuery에서 입력 값 설정

이 튜토리얼은 jQuery에서 입력 값을 설정하는 방법을 보여줍니다.

이 페이지의 내용

jQuery에서 val() 메서드를 사용하여 jQuery의 입력 필드 값을 설정할 수 있습니다. 이 튜토리얼은 val() 메소드를 사용하여 jQuery에서 입력 필드의 값을 설정하는 방법을 보여줍니다.

jQuery에서 입력 값 설정

val()은 주어진 요소의 값을 반환하거나 설정하는 데 사용되는 jQuery의 내장 메서드입니다. 이 메서드가 값을 반환하는 경우 첫 번째 선택한 요소의 값이 됩니다.

이 방법을 사용하여 요소의 값을 설정하는 경우 해당 값은 하나 이상의 요소에 대해 설정할 수 있습니다. 이 방법은 세 가지 다른 방법으로 사용할 수 있습니다.

  1. 먼저 요소의 값을 반환합니다.

    통사론:

    $(selector).val()
    
  2. 요소의 값을 설정합니다.

    통사론:

    $(selector).val("value")
    
  3. 함수를 사용하여 값을 설정합니다.

    통사론:

    $(selector).val(function(index, CurrentValue))
    

    여기서 선택자는 요소의 ID, 클래스 또는 이름일 수 있으며 은 새 값으로 사용할 값입니다. IndexCurrentValue는 집합에서 요소 인덱스의 위치와 선택한 요소의 현재 값을 반환합니다.

입력 필드의 값을 반환하는 간단한 예를 들어 보겠습니다.

예제 코드:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title> jQuery Val() Method</title>
    <style>
        p {
        color: green;
        margin: 10px;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>

    <input type="text" placeholder="Type Something">
    <p></p>

    <script>
        $( "input" ).keyup(function() {
            var Input_Value = $( this ).val();
            $( "p" ).text( Input_Value );
        }).keyup();
   </script>

</body>
</html>

위의 코드는 입력 필드의 값을 반환하고 주어진 단락에 씁니다.

출력:

jQuery 반환 입력 값

이제 val() 메소드를 사용하여 입력 필드의 값을 설정해 보겠습니다.

예제 코드:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>jQuery val() Method</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#DemoInput").val("https://www.delftstack.com/");
        });
    </script>
</head>
<body>
    <h1> jQuery Val() Method</h1>
    <label>Enter Your Site:</label>
    <input type="text" id="DemoInput">
</body>
</html>

위의 코드는 주어진 입력 값을 https://www.delftstack.com/으로 설정합니다.

출력:

JQuery 설정 입력 값

함수와 함께 val() 메서드를 사용합시다.

예제 코드:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jQuery val() Method</title>
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
    <h1> jQuery Val() Method</h1>
    <p>Type anything and it will be converted into Uppercase.</p>
    <p>Type and click outside.</p>
    <input type="text" placeholder="type anything">

    <script>
        $( "input" ).on( "blur", function() {
            $( this ).val(function( x, Input_Value ) {
                return Input_Value.toUpperCase();
            });
        });
    </script>

</body>
</html>

위의 코드는 입력 필드의 값을 대문자로 변환합니다.

출력:

함수로 JQuery 설정 입력 값