Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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

like image 969
AnApprentice Avatar asked Dec 02 '10 19:12

AnApprentice


2 Answers

$('#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 ? ', ' : '')
like image 148
user113716 Avatar answered Oct 22 '22 10:10

user113716


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);
like image 40
Aaron Hathaway Avatar answered Oct 22 '22 09:10

Aaron Hathaway