To append an element with a text message when the input field is changed, change() and appendTo() methods are used. The change() method is used to detect the change in the value of input fields.
To add text to a textarea, access the value property on the element and set it to its current value plus the text to be appended, e.g. textarea. value += 'Appended text' . The value property can be used to get and set the content of a textarea element. Here is the HTML for the examples in this article.
$('#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" />
There are two options. Ayman's approach is the most simple, but I would add one extra note to it. You should really cache jQuery selections, there is no reason to call $("#input-field-id")
twice:
var input = $( "#input-field-id" );
input.val( input.val() + "more text" );
The other option, .val()
can also take a function as an argument. This has the advantange of easily working on multiple inputs:
$( "input" ).val( function( index, val ) {
return val + "more text";
});
If you are planning to use appending more then once, you might want to write a function:
//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);
}
After you can just call it:
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>
Well when creating this example I somehow got a little confused. "ValueText" vs >Current NodeText< Isn't .val()
supposed to run on the data of the value attribute? Anyway I and you me may clear up this sooner or later.
However the point for now is:
When working with form data use .val().
When dealing with the mostly read only data in between the tag use .text() or .append() to append text.
You are probably looking for val()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With