qarar qarar -4 years ago 94
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.


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


$('.dropdown-container-multiple ul li').click(function(){

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.

Answer Source

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

$('.dropdown-container-multiple ul li').click(function(){
    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(){
    var texts = $(".dropdown-container-multiple ul").map(function() {
        return $(this).text();
    }).get().join(" ");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download