Home > other >  How can i take a mutiples value from selected option and put into text area with line break
How can i take a mutiples value from selected option and put into text area with line break

Time:09-23

I already using this code block

<div class="col-12 col-md-12 col-sm-12">
    <small>Clique para selecionar e/ou retirar um produto desejado</small>
    <select name="id_produtos" data-label="Produtos" id="produtos" class="form-control show-tick pl-4 pr-4 pb-4 " data-live-search="true" multiple>
        <option value="" disabled>Selecione um produto</option>
        @foreach (var item in Model.Produtos)
        {
            <option value="@item.id_produto">@item.nome</option>
        }
    </select>
    <small>Produtos Selecionados</small>
    @*<label id="produtos-selecionados" class="mm-yyyy form-control"> </label>*@
    <textarea id="produtos-selecionados" class="mm-yyyy form-control" rows="10" cols="40"  minlength="10" maxlength="25" readonly></textarea>
</div>

and this script:

$('select[name="id_produtos"]').change(function () {
        var text = $(this).find("option:selected").text();
        if (text != "") {
            text = text;

        }

        $('#produtos-selecionados').val(text);
    });

But didn't take a line break in text area.

Please help me guys, thanks BTW.

CodePudding user response:

$(this).find("option:selected") would get one or more elements. So the .text() on more than one element might by problematic. You might be able to do this with jQuery's .map().get().join() chain. This way you have more control of the line break characters in between the values.

Like so:

$('select[name="id_produtos"]').change(function() {
    var v = $(this).find('option:selected') // Get all selected options
    .map(function() { // For each option return the label text only
        return this.innerText; // or use this.value if that's what you want
    })
    .get() // Get as an array
    .join("\n"); // Join/glue together with line breaks

    $('textarea').val( v ); // Set textarea contents
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="id_produtos" multiple>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

<textarea rows="5"></textarea>

  • Related