JQuery get remaining OPTION values ​​in CSV format

I want to return a CSV formatted string to set the value of an input textbox with OPTION values ​​from a SELECT window.

$. map ($ ('# addedchargeamtid option'), function (e) {var exp = $ (E) .text (); alarm (Exp);})

When using the map function, but it looks to overwrite the value every time. can't figure out how to do it.

BTW thanks to all the jQuery gurus today, lots of props for my problems !!!

UPDATE:

<option value="123">123</option>
<option value="asd">asd</option>
<option value="trr">trr</option>
<option value="345">345</option>

      

I need this:

123, ASD, TRR, 345

But the parameters are dynamic and can be added or removed, so it can be 1 or 100

NEW:

Good thing it works. it gives me 4 options for the same element when I only added them once. also doesn't update hidden textbox with CSV value

// Add remove button
$('#addButton').click(function() {
   $('#removeButton').show();

   // Add 
   var myOptions = $('#typedchargeamtid').val();
   $.each(myOptions, function() {
      $('#addedchargeamtid').append(
         $('<option></option>').val(myOptions).html(myOptions)
      );
   });

   var txt = $('#addedchargeamtid').val() || [];
      $('#commasepchargeamtid').val(txt.join(','));
   });

      

Thanks again

+1


a source to share


2 answers


You can use each instead of a map:



    var options = Array();
    $('#addedchargeamtid option').each(function(index){
        options[index] = $(this).val();
    });

    $('#commasepchargeamtid').val(options.join(','));

      

+6


a source


The jQuery documentation states that the $ .val () function when used in a select will return a list of the selected values. Just simply using what s array.join

should accomplish what you are looking for, I believe.

var txt = $('#addedchargeamtid option').val() || [];
$('#myinputbox').val(txt.join(','));

      



Or is there a function array.reduce in Javascript 1.8

var txt = $('#addedchargeamtid option').val() || [];
$('#myinputbox').val(txt.reduce(
   function(prev, next, index, array){
       return prev + "," + next;
   },
   '')
);

      

0


a source







All Articles