Code Lover Code Lover - 5 months ago 31
jQuery Question

jQuery get multiple select items value on select

I want to get all multiselect items value and based on that I am going to create dropdown list with the selected items.

My HTML is as below

<div>
<form action="" method="post">
<label for="title">Title</label>
<input type="text" name="title" value="" placeholder="Your title" />
<label for="cars">Select Cars</label>
<select name="cars" id="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="submit" value="Submit">
</form>
</div>


I am trying to use below jQuery

$(document).ready(function(){
$('#cars').change(function(){
$(this).after('<p>' + $('#cars').val() + '</p>');
})
});


This is giving me selected items value but than it is giving me in rows of all occurrence. I don't know how to say it but please see below image.

enter image description here

But I want only final result all the time and not one by one occurrence. Hope I explain it properly. :)




I want to convert after() paragraph to Dropdown select with the selected item. So is it possible to use php explode for it or any other way in jquery itself?

Final Output I am looking for is

<div>
<form action="" method="post">
<label for="title">
Title</label>
<input type="text" name="title" value="" placeholder="Your title" />
<label for="cars">
Select Cars</label>
<select name="cars" id="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>

<select name="sortedcars" id="sortedcars">
<option value="volvo">Volvo</option>
<option value="audi">Audi</option>
</select>

<input id="create" type="button" value="CreateDropDown">
</form>
</div>

Answer

probably this may help you

<script>
    $(document).ready(function () {
        $('#cars').click(function () {
            var values = $("#cars").val();
            var select = $("<select/>");
            for (i = 0; i < values.length; i++) {
                select.append($("<option/>", { html: values[i] }));
            }
            $("#dropdownDiv").html("");
            $("#dropdownDiv").append(select);
        })
    });
</script>
<body>
    <div>
        <form action="" method="post">
        <label for="title">
            Title</label>
        <input type="text" name="title" value="" placeholder="Your title" />
        <label for="cars">
            Select Cars</label>
        <select name="cars" id="cars" multiple>
            <option value="volvo">Volvo</option>
            <option value="saab">Saab</option>
            <option value="opel">Opel</option>
            <option value="audi">Audi</option>
        </select>
        <input id="create" type="button" value="CreateDropDown">
        <div id="dropdownDiv">
        </div>
        </form>
    </div>
</body>