jQuery - 将值附加到 INPUT,使其保持逗号分隔列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4339066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - Append a Value to a INPUT, keeping it a Comma Delimited list
提问by AnApprentice
I have an input like follows:
我有如下输入:
<input type="hidden" id="attachment-uuids" value="">
I'd like to be able to append a value to the Input, at different times:
我希望能够在不同的时间向输入附加一个值:
$('#attachment-uuids).val('55555');
results in:
结果是:
<input type="hidden" id="attachment-uuids" value="55555">
But then doing:
但是然后做:
$('#attachment-uuids).val('66666');
results in:
结果是:
<input type="hidden" id="attachment-uuids" value="66666">
Where I'd like the following:
我想要以下内容:
<input type="hidden" id="attachment-uuids" value="55555, 66666">
how can I append values when the value is empty and when the value is not empty with a comma delimited list?
当值为空且值不为空时,如何使用逗号分隔列表附加值?
Thanks
谢谢
回答by user113716
$('#attachment-uuids').val(function(i,val) {
return val + (!val ? '' : ', ') + '66666';
});
EDIT:As @mkoryaknoted, I'm doing an unnecessary negation of val
in the conditional operator. It could be rewritten without the !
as:
编辑:正如@mkoryak 所指出的,我val
在条件运算符中做了一个不必要的否定。它可以在没有!
as 的情况下重写:
(val ? ', ' : '')
回答by Aaron Hathaway
Just add a conditional when you add the value to the field.
只需在将值添加到字段时添加条件即可。
var cur_val = $('#attachment-uuids').val();
if(cur_val)
$('#attachment-uuids').val(cur_val + "," + new_val);
else
$('#attachment-uuids').val(new_val);
回答by roni
Append won't work for input. But you can use:
附加不适用于输入。但是你可以使用:
$("#txt1").get(0).value+="+";
回答by user1973805
I believe the .append()
function is exactly for this purpose. I just tried:
我相信该.append()
功能正是为此目的。我刚试过:
$("#attachment-uuids").append(new_val);
to append values to a field. This works and "attachment-uuids" is populated with CSVs, as required.
将值附加到字段。这有效,并且“attachment-uuids”根据需要填充了 CSV。