programing

입력 필드에 텍스트 추가

jooyons 2023. 8. 18. 22:31
반응형

입력 필드에 텍스트 추가

입력 필드에 텍스트를 추가해야 합니다.

    $('#input-field-id').val($('#input-field-id').val() + 'more text');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="input-field-id" />

두 가지 옵션이 있습니다.아이만의 접근법이 가장 간단하지만, 저는 여기에 하나의 메모를 추가하고 싶습니다.jQuery 선택 항목을 캐시해야 합니다. 호출할 이유가 없습니다.$("#input-field-id")두 번:

var input = $( "#input-field-id" );
input.val( input.val() + "more text" );

다른 옵션은 함수를 인수로 사용할 수도 있습니다.이는 여러 입력에 대해 쉽게 작업할 수 있는 장점이 있습니다.

$( "input" ).val( function( index, val ) {
    return val + "more text";
});

추가 기능을 한 번 이상 사용하려는 경우 다음과 같은 기능을 작성할 수 있습니다.

//Append text to input element
function jQ_append(id_of_input, text){
    var input_id = '#'+id_of_input;
    $(input_id).val($(input_id).val() + text);
}

전화를 걸면 다음과 같이 됩니다.

jQ_append('my_input_id', 'add this text');

	// Define appendVal by extending JQuery
	$.fn.appendVal = function( TextToAppend ) {
		return $(this).val(
			$(this).val() + TextToAppend
		);
	};
//_____________________________________________

	// And that's how to use it:
	$('#SomeID')
		.appendVal( 'This text was just added' )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<textarea 
          id    =  "SomeID"
          value =  "ValueText"
          type  =  "text"
>Current NodeText
</textarea>
  </form>

이 예를 만들 때 저는 약간 혼란스러웠습니다."ValueText" vs. >현재 노드 텍스트< 그렇지 않습니다..val()가치 속성의 데이터에서 실행되어야 합니까?어쨌든 저와 당신은 조만간 이 문제를 해결할 것입니다.

하지만 지금 요점은 다음과 같습니다.

폼 데이터로 작업할 때는 .val()을 사용합니다.

태그 사이에 있는 대부분의 읽기 전용 데이터를 처리할 때 텍스트를 추가하려면 .text() 또는 .append()를 사용합니다.

당신은 아마도 val()찾고 있을 것입니다.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <style type="text/css">
        *{
            font-family: arial;
            font-size: 15px;
        }
    </style>
</head>
<body>
    <button id="more">More</button><br/><br/>
    <div>
        User Name : <input type="text" class="users"/><br/><br/>
    </div>
    <button id="btn_data">Send Data</button>
    <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('#more').on('click',function(x){
                var textMore = "User Name : <input type='text' class='users'/><br/><br/>";
                $("div").append(textMore);
            });

            $('#btn_data').on('click',function(x){
                var users=$(".users");
                $(users).each(function(i, e) {
                    console.log($(e).val());
                });
            })
        });
    </script>
</body>
</html>

출력

언급URL : https://stackoverflow.com/questions/841722/append-text-to-input-field

반응형