我需要在输入字段中附加一些文本...
问问题
294416 次
6 回答
220
$('#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" />
于 2009-05-08T20:50:22.053 回答
116
有两种选择。Ayman 的方法是最简单的,但我会在其中添加一个额外的注释。你真的应该缓存 jQuery 选择,没有理由调用$("#input-field-id")
两次:
var input = $( "#input-field-id" );
input.val( input.val() + "more text" );
另一个选项,.val()
也可以将函数作为参数。这具有轻松处理多个输入的优点:
$( "input" ).val( function( index, val ) {
return val + "more text";
});
于 2011-07-30T20:39:38.253 回答
17
如果您打算多次使用附加功能,您可能需要编写一个函数:
//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');
于 2009-05-08T21:00:58.737 回答
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>
好吧,在创建这个示例时,我不知何故有点困惑。“ ValueText ” vs > Current NodeText < 不.val()
应该在value属性的数据上运行吗?无论如何,我和你我迟早会解决这个问题。
然而,现在的重点是:
处理表单数据时使用.val()。
于 2016-08-12T14:42:23.283 回答
4
您可能正在寻找val()
于 2009-05-08T20:51:17.790 回答
0
<!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>
于 2016-11-11T09:42:57.160 回答