akkapolk akkapolk - 2 months ago 14
jQuery Question

Get selected text of a dropdown's item and split by new line and then show alert result using jQuery

Get selected text of a dropdown's item and split by new line and then show alert result using jQuery

Sample dropdown's item

Value Text
1 AAA
2 BBBB
3 CCCCC


Get the currently selected text:

var selectedItText = $("#dropDownId option:selected").text();
// Get AAABBBBCCCCC


Show alert result

alert(selectedItemValue);
// Show "AAABBBBCCCCC"
// But I want "AAA\nBBBB\n\CCCCC" How to split selectedItText by new line?


I'm sorry for less information, I change Text from "A" to "AAA", "B" to "BBBB" and "C" to "CCCCC".

Answer Source

Try this :

alert(selectedItemValue.split('').join('\n'));

Update

$('#dropDownId').change(function(){
var results="";
$('#dropDownId :selected').each(function(index, sel){ 
   results+= $(sel).text()+'\n'; 
});

alert(results);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<select id="dropDownId" multiple="multiple" name="multiple">
  <option value=""> -- Select -- </option>
  <option value="1">AAA</option>
  <option value="2">BBB</option>
  <option value="3">CCC</option>
 </select>