1

I have a simple HTML form:

<form>
<select class="form-control" name="select-1615762852985[]" multiple="true" id="select-1615762852985">
<option value="20" selected="true" id="select-1615762852985-0">Option 1</option>
<option value="20" id="select-1615762852985-1">Option 2</option></select>
</form>

I'm using this code to get option text.

var selected = $('#'+label_id).find('option:selected').text();

When a single choose is selected the result is correct: "Option 1" or "Option 2"

However when you select both at the same time, the result is concatenated together "Option 1Option 2", "Option 1Option 2"

Is there a way to do this without concatenating the results?

Scott Paterson
  • 141
  • 3
  • 13

2 Answers2

3

You can use map() to build an array of the text from the selected option elements:

$('form').on('submit', e => {
  e.preventDefault();
  let selected = $(e.target).find('select option:selected').map((i, opt) => opt.textContent).get();
  console.log(selected);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <select class="form-control" name="select-1615762852985[]" multiple="true" id="select-1615762852985">
    <option value="20" selected="true" id="select-1615762852985-0">Option 1</option>
    <option value="20" id="select-1615762852985-1">Option 2</option>
  </select>
  <button type="submit">Submit</button>
</form>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

Just vanilla JS solution, use querySelectorAll to fetch all options and use ... spread operator to make an array, then map only selected values.

var sel = [...document.querySelectorAll("#select-1615762852985 option")].map(s => s.selected ? s.text : []).flat()


console.log(sel)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <select class="form-control" name="select-1615762852985[]" multiple="true" id="select-1615762852985">
    <option value="20" selected="true" id="select-1615762852985-0">Option 1</option>
    <option value="20" id="select-1615762852985-1" selected="true">Option 2</option>
    <option value="20" id="select-1615762852985-1">Option 3</option>

  </select>
</form>

Or like this:

var sel = [...document.querySelectorAll("#select-1615762852985 option")].filter(s => s.selected).map(s=>s.text)
ikiK
  • 6,328
  • 4
  • 20
  • 40