I need to append some text to an input field...
问题:
回答1:
$('#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" />
回答2:
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";
});
回答3:
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');
回答4:
You are probably looking for val()
回答5:
// 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.
回答6:
<!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>
Output