将文本附加到输入字段

我需要在输入栏中添加一些文本..。

306765 次浏览

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

你可能正在寻找 Val ()

如果计划多次使用附加,可能需要编写一个函数:

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

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" );

另一个选项 .val()也可以将函数作为参数。这样做的好处是可以方便地处理多个输入:

$( "input" ).val( function( index, val ) {
return val + "more 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>

在创建这个例子的时候,我有点困惑。“ 价值短信”vs > 当前节点文本 < .val()不是应该在 价值属性的数据上运行吗?无论如何,我和你我迟早会弄清楚的。

不过,目前的关键是:

使用 表格数据时使用 Rel = “ norefrer”> . val ()

When dealing with the mostly 只读数据 in between the tag use Rel = “ norefrer”> . text () or Rel = “ norefrer”> . append () to append text.

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

输出 enter image description here