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

AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

4 Answers4

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 ? ', ' : '')
Community
  • 1
  • 1
user113716
  • 318,772
  • 63
  • 451
  • 440
11

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);
Aaron Hathaway
  • 4,280
  • 2
  • 19
  • 17
0

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

$("#txt1").get(0).value+="+";
Smern
  • 18,746
  • 21
  • 72
  • 90
roni
  • 51
  • 7
-4

I believe the .append() function is exactly for this purpose. I just tried:

$("#attachment-uuids").append(new_val); 

to append values to a field. This works and "attachment-uuids" is populated with CSVs, as required.

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208