jQuery - 将值附加到INPUT,使其保持为逗号分隔列表

时间:2021-01-20 14:26:51

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

4 个解决方案

#1


39  

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

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

编辑:正如@mkoryak所说,我在条件运​​算符中做了一个不必要的val否定。它可以在没有!的情况下重写!如:

(val ? ', ' : '')

#2


9  

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

#3


0  

Append won't work for input. But you can use:

追加不适用于输入。但你可以使用:

$("#txt1").get(0).value+="+";

#4


-4  

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.

将值附加到字段。这样可以工作,并且根据需要使用CSV填充“attachment-uuids”。

#1


39  

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

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

编辑:正如@mkoryak所说,我在条件运​​算符中做了一个不必要的val否定。它可以在没有!的情况下重写!如:

(val ? ', ' : '')

#2


9  

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

#3


0  

Append won't work for input. But you can use:

追加不适用于输入。但你可以使用:

$("#txt1").get(0).value+="+";

#4


-4  

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.

将值附加到字段。这样可以工作,并且根据需要使用CSV填充“attachment-uuids”。