dmcs14db dmcs14db - 1 month ago 11
Javascript Question

How to separate by pipe for multiple select in hidden field

I have a form that has 3 drop downs to make selections, the first drop down allows the user to select a specific Type, the second box, the user must select a date which will then present users with the filtered options on the 3rd drop down which is done in Jquery. I had it working where the user only selects one option in the 3rd drop down.

Now I would like the user to select multiple options. The code below is what I used to get the single selection to update the hidden field and pass via form submission.

The below code minus the ".join('|')" outputs the values into the hidden field then it gets passed into a data storage via POST.

This is my code:

$('#TopicID').on('change',function()
{ TIDval.val( $(this).find(':selected').text().join('|') );
});


I tried several versions to get it to work if I remove the ".join('|')" the output gives me all of the values concatenated.

Value 1: tree
Value 2: boat
Value 3: car

The output is as follows: treeboatcar

but I need: tree|boat|car

I have updated my new code to reflect the solution suggested by Loading... in this thread to the following.

$('#TopicID').change(function(){
var selectedText = $(this).find(':selected').map(function(){
return $(this).text(); //$(this).val()
}).get().join('|');

$("#TopicID_value").text(selectedText);
});


Which now updates the hidden field value correctly with the pipe separated values but the value is no longer passed in the POST call when submitted in the form.

The hidden field



In firebug I see the value being updated properly when I select one or multiple options but for some reason the value gets lost in the submission process. I don't see much of a different where that could happen.

Answer

Use map()

$('#TopicID').change(function(){
   var selectedText = $(this).find(':selected').map(function(){
       return $(this).text(); //$(this).val()
   }).get().join('|');
   console.log(selectedText);
});

$('#TopicID').change(function(){
var selectedText = $(this).find(':selected').map(function(){
   return $(this).text(); //$(this).val()
}).get().join('|');
console.log(selectedText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="TopicID" multiple="true">
 <option id="1">ABC</option>
 <option id="2">XYZ</option>
 <option id="3">PQR</option>
</select>

Comments