jQuery-将值附加到INPUT,使其保持逗号分隔列表 [英] jQuery - Append a Value to a INPUT, keeping it a Comma Delimited list

查看:163
本文介绍了jQuery-将值附加到INPUT,使其保持逗号分隔列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的输入如下:

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

导致:

<input type="hidden" id="attachment-uuids" value="55555">

但是然后做:

$('#attachment-uuids).val('66666');

导致:

<input type="hidden" id="attachment-uuids" value="66666">

我想要以下内容:

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

谢谢

推荐答案

$('#attachment-uuids').val(function(i,val) { 
     return val + (!val ? '' : ', ') + '66666';
});


编辑:正如 @mkoryak 所述,我正在对val在条件运算符中.不用!可以将其重写为:


As @mkoryak noted, I'm doing an unnecessary negation of val in the conditional operator. It could be rewritten without the ! as:

(val ? ', ' : '')

这篇关于jQuery-将值附加到INPUT,使其保持逗号分隔列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆