Pregunta

Necesito agregar texto a un campo de entrada ...

¿Fue útil?

Solución

    $('#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" />

Otros consejos

Hay dos opciones. El enfoque de Ayman es el más simple, pero agregaría una nota adicional. Realmente debería almacenar en caché las selecciones de jQuery, no hay razón para llamar $("#input-field-id") dos veces:

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

La otra opción, .val() también puede tomar una función como argumento. Esto tiene la ventaja de trabajar fácilmente en múltiples entradas:

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

Si planea usar el apéndice más de una vez, es posible que desee escribir una función:

//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);
}

Después de que simplemente puedas llamarlo:

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

Probablemente esté buscando val ()

	// 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>

Bueno, al crear este ejemplo, de alguna manera me confundí un poco. " ValueText " vs > Texto de nodo actual < ¿No se supone que .val() se ejecuta en los datos del atributo value ? De todos modos, tú y yo podemos aclarar esto tarde o temprano.

Sin embargo, el punto por ahora es:

Cuando trabaje con datos de formulario use .val () .

Cuando se trata de la mayoría de los datos de solo lectura entre la etiqueta, use .text () o .append () para agregar texto.

<!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>

Salida ingrese la descripción de la imagen aquí

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top