Alex Rivera | Logout

jQuery - Append a Value to a INPUT, keeping it a Comma Delimited list

Asked 2010-12-02T19:39:21.673
16

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

Edit
Report

1 Answer

42
$('#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:

(val ? ', ' : '')
answered 2010-12-02T19:42:53.840

Your Answer