qarar qarar - 3 months ago 12
jQuery Question

want to insert multiple values on select

I am trying to select multiple options from list and then want to insert those values in an input field. What I have done so far.

HTML:

<div class="input-container">
<label>preffered country</label>
<div class="dropdown-container-multiple">
<input type="text" name="pc" placeholder="please select" required />
<span></span>
<ul name="country" class="multiple">
<li>I don't know</li>
<li>Italy</li>
<li>Spain</li>
<li>Switzerland</li>
<li>Turkey</li>
</ul>
</div>
</div>


Jquery:

$('.dropdown-container-multiple ul li').click(function(){
$(this).toggleClass('active');
$(this).parent('ul').parent('.dropdown-container-multiple').find('input').val($(this).text());
});


This is doing good for single value option but I tried what I knew but it didn't work for multiple selection

any help will be appreciated.
Thanks

Answer

You need to concatenate to the old value, not just replace it.

$('.dropdown-container-multiple ul li').click(function(){
    $(this).toggleClass('active');
    var text = $(this).text();
    $(this).parent('ul').parent('.dropdown-container-multiple').find('input').val(function(i, oldval) {
        return oldval == '' ? text : oldval + " " + text;
    });
});

To be able to add and remove items from the input, join all the texts from the active elements.

$('.dropdown-container-multiple ul li').click(function(){
    $(this).toggleClass('active');
    var texts = $(".dropdown-container-multiple ul li.active").map(function() {
        return $(this).text();
    }).get().join(" ");
    $(this).parent('ul').parent('.dropdown-container-multiple').find('input').val(texts);
});
Comments