tags:

views:

230

answers:

2

I'm looking to return a CSV formatted string to set the value of a input text field with the OPTION values from a SELECT box.

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

In using a map function but it looks to overwrite the value each time. can't figure out how to concat these together somehow.

BTW thanks to all the jQuery Gurus today, much props on my issues!!!

UPDATING:

<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 options are dynamic and can be added or removed, so there could be 1 or 100

NEW:

Well this is kinda working. it gives me 4 options of the same item when I only added it once. also does not update the hidden text field with the 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

A: 

The JQuery documentation states that the $.val() function when used on a select will return a list of selected values. Just simply using that with an array.join should accomplish what you are looking for I believe.

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

Or there is an array.reduce function in Javascript 1.8

var txt = $('#addedchargeamtid option').val() || [];
$('#myinputbox').val(txt.reduce(
   function(prev, next, index, array){
       return prev + "," + next;
   },
   '')
);
Danny
thnx I have made some changes to the code but still not working
Phill Pafford
+1  A: 

You can use each instead of map:

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

    $('#commasepchargeamtid').val(options.join(','));
Nadia Alramli
trying to incorporate this as well but not working
Phill Pafford
I tested the code in the answer and it is working for sure. Can you explain what is not working about it?
Nadia Alramli
after refactoring my code I got this to work, Awesome Thanks :)
Phill Pafford