How to return selected items in a <select Multiple> with jQuery

Asked

Viewed 268 times

-8

I need to receive the values of a comma separated $('select[Multiple]'). val(). For example.

The HTML code:

<select id="estado" multiple>
<option selected>SP</option>
<option selected>RJ</option>
<option selected>ES</option>
<option>MG</option>
</select>

Javascript code with jQuery:

const estados = $('#estado').val(); //Resultado: SPRJES    

How to make the return of states to be "SP, RJ, ES" if these were selected?

It’s all coming back together.

Thank you

  • As the return is now?

  • Explain better what you want to do, show more code. Give an example of an entry and what would be the desired result.

  • Erlon, I applied to a select of multiple choice, it returns everything together, SP,RJ,ES,MG, I need a space between them, e.g.: SP, RJ, ES

  • They denied my question why? If it’s so banal why didn’t they help me?

  • 1

    Speak, friend. I improved the writing of your question. Ended up annoying some rsrsrs. I put the answer you need. Look there.

  • Thanks again Sergio, I tried to be brief, I did not think the question was poorly asked, but with its edition got better! Thanks!

Show 1 more comment

1 answer

1


What you need is to use the array function join.

See how it looks in this example: https://jsfiddle.net/7tfcyjuv/

HTML:

<select id="estado" multiple>
<option>SP</option>
<option>RJ</option>
<option>ES</option>
<option>MG</option>
</select>

Javascript code with your request:

const estados = $('#estado').val().join(', '); //Resultado: SP, RJ, ES
  • 1

    Perfect Sergio! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.