How do I keep the order of selection when using multiple select in HTML form?

I need to have the User selected ordered preference of selected items from a drop down list.
By default they're returned in dataset order, regardless of selection order.

<select name="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">
Above example always returns top down order - audi can never be 1st.
Thank you,
Russ
Russ CummingsIT ConsulantAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Michael McDermottCommented:
The code above is the Html code where is the PHP that generates the list? For this to work you are going to have to
1. Use Php to pull the cars from your data source order if you like
2. Use a loop to write out the html structure you have above be sure to put selected in the tag the user selected eg

<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="vw">VW</option>
  <option value="audi" selected>Audi</option>
</select>
0
Shaun VermaakTechnical Specialist/DeveloperCommented:
I know topic is PHP but if you want to do it via JQuery

HTML
<select id="ddlList">
    <option value="3">Three</option>
    <option value="1">One</option>
    <option value="1">one</option>
    <option value="1">a</option>
    <option value="1">b</option>
    <option value="1">A</option>
    <option value="1">B</option>
    <option value="0">Zero</option>
    <option value="2">Two</option>
    <option value="8">Eight</option>
</select>
<input type="button" id="btnSort" Value=" Sort Dropdown By Text " />

Open in new window


JS
//, attr, order

var sortSelect = function (select, attr, order) {
    if(attr === 'text'){
        if(order === 'asc'){
            $(select).html($(select).children('option').sort(function (x, y) {
                return $(x).text().toUpperCase() < $(y).text().toUpperCase() ? -1 : 1;
            }));
            $(select).get(0).selectedIndex = 0;
            e.preventDefault();
        }// end asc
        if(order === 'desc'){
            $(select).html($(select).children('option').sort(function (y, x) {
                return $(x).text().toUpperCase() < $(y).text().toUpperCase() ? -1 : 1;
            }));
            $(select).get(0).selectedIndex = 0;
            e.preventDefault();
        }// end desc
    }

};

//, attr, order
$(document).ready(function () {

    $('#btnSort').click(function (e) {

        sortSelect('#ddlList', 'text', 'asc');

    }); // event listener click

});

Open in new window

https://codepen.io/AlexBezuska/pen/kCwvJ
0
Chris StanyonWebDevCommented:
If I've read you question correctly (and differently to the other users), then what you want to do can't be done using the type of code you currently have. When the form is submitted, it will simply contain a list of items the user selected. It won't show you the order in which they selected them. You would need to design your UI in a different way. For example, you would need a list of available options, such as what you already have, and then a button for example to add a single item to a 'preferred' list. Then as the user added each item to the preferred list, that list would be submitted in the order the user selected the items.

If I've misread your question, then ignore me :) If I haven't and you need more help, let me know.
0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Russ CummingsIT ConsulantAuthor Commented:
Now I'm confused. When I do:
       
 $cars= implode(', ',$_POST['cars']);

echo $cars;
I get -
Volvo, Audi

I always get the order as if they were selected top to bottom from the list (as entered above).
What I want to see is the php variable $cars in the exact order the user selected them.
No need to redisplay the list, just fill the $cars variable with $cars[0], $cars[1] etc.
Where $cars[0] is 1st selected, $cars[1] is 2nd selected, $cars[2] is 3rd selected.

Thanks,
Russ
0
Russ CummingsIT ConsulantAuthor Commented:
After doing research I understand I will have to use something other than just HTML & php (ajax, jquery, etc) - that's quite alright.
Willing to learn, never really used them before - need guidance.
Thank you again,

Russ
0
Chris StanyonWebDevCommented:
Hey Russ,

That's what I was alluding too. There are a few ways to do this, but take a look at the following HTML:

<div id="carOptions">
    <select id="available" size="5">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="opel">Opel</option>
        <option value="audi">Audi</option>
    </select>

    <div id="buttons">
        <button id="add">Add >></button>
        <button id="remove"><< Remove</button>
    </div>

    <select id="selected" size="5"></select>
</div>

<input type="text" name="selectedCars">

Open in new window

We have a list of Available Cars, and empty list of Selected Cars, Add / Remove buttons, and a text box called selectedCars. Now take a look at the following jQuery:

$(document).ready(function() {

    // Add a Car to the Selected List
    $('#add').click(function(e) {
        e.preventDefault();
        // Make sure the Car is not already in the list of Selected Cars
        if ($("#selected option").filter(function (i, o) { return o.value === $('#available option:selected').val(); }).length === 0)
        {
            $('#selected').append($('#available option:selected').clone());
            buildList();
        }
    });

    // Remove a Car from the Selected List
    $('#remove').click(function(e) {
        e.preventDefault();
        $('#selected option:selected').remove();
        buildList();
    });

    // Build the list of Selected Cars
    function buildList() {
        var cars = [];

        $('#selected option').each(function(i,e) {
            cars.push($(this).val());
        });

        $("input[name='selectedCars']").val(cars.join());
    }
    
});

Open in new window

We have 3 functions - one for adding the selected car, one for removing the selected car, and one for building a text list of selected cars (in order). You'll notice in the HTML that only the selectedCars has a name attribute. This means that the actual <select> boxes won't be submitted along with the form - only the selectedCars text box will - you'll want to make that hidden. When the form is submitted, you will then get a text value of all the selected cars in the correct order.
0
Russ CummingsIT ConsulantAuthor Commented:
Chris,
 Thank you for the detailed explanation.  Below you'll see the complete sample program.
The problem I'm still having is how I grab the selectedCars variable.
For now all I want to do is echo the selectedCars to confirm selection & order, then I'm truly good to go.
Please let me know what I'm not understanding.

<?php
session_start();
ob_clean();
ob_start();
// define variables and set to empty values
$selectedCars = "";
$status = "";

if(isset($_POST['new']) && $_POST['new']==1)
{
$selectedCars =$_REQUEST['selectedCars'];
echo "List of cars - ". $selectedCars;
}
?>
<!DOCTYPE html>

<html>
<head>
	<meta charset="utf-8">
	<title>Sample</title>
</head>
<body>

<form name="form" method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"> 
<input type="hidden" name="new" value="1" />
<div id="carOptions">
    <select id="available" size="5">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="opel">Opel</option>
        <option value="audi">Audi</option>
    </select>

    <div id="buttons">
        <button id="add">Add >></button>
        <button id="remove"><< Remove</button>
    </div>

    <select id="selected" size="5"></select>
</div>

<input type="text" name="selectedCars">
<input type="submit" name="submit" value="Submit">
</form>



<script>
$(document).ready(function() {

    // Add a Car to the Selected List
    $('#add').click(function(e) {
        e.preventDefault();
        // Make sure the Car is not already in the list of Selected Cars
        if ($("#selected option").filter(function (i, o) { return o.value === $('#available option:selected').val(); }).length === 0)
        {
            $('#selected').append($('#available option:selected').clone());
            buildList();
        }
    });

    // Remove a Car from the Selected List
    $('#remove').click(function(e) {
        e.preventDefault();
        $('#selected option:selected').remove();
        buildList();
    });

    // Build the list of Selected Cars
    function buildList() {
        var cars = [];

        $('#selected option').each(function(i,e) {
            cars.push($(this).val());
        });

        $("input[name='selectedCars']").val(cars.join());
    }
    
});
</script>

</body>
</html>

Open in new window


Thank you,

Russ
0
Chris StanyonWebDevCommented:
Hey Russ - you're almost there, but you need to include the jQuery library in the <head> of your page. It's also common practice to put the <script> tag in the head also:

<html>
<head>
	<meta charset="utf-8">
	<title>Sample</title>
	<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
	<script>
		$(document).ready(function() {
			...
		});
	</script>
</head>
<body>
   ...

Open in new window

Also bear in mind that you're actually trying to echo out the result, before the opening DOCTYPE. You should really echo it out in the main body of your page.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Russ CummingsIT ConsulantAuthor Commented:
Chris,
Got it. Works! just to ask - Would there be any way of doing this without "ADD" button?
Reason is this is actually in the middle of a complex form & it breaks up the flow.
But, if not, you have my thanks & full acknowledgement that you're the best.
Russ
0
Chris StanyonWebDevCommented:
Hey Russ,

Glad it's working.

Potentially there are a few ways you could do this, but you'd want to take your users and the UI design into account, and offer your users a simple, clear and intuitive way for them to add their choices. You'd also probably want to ensure it works across all devices, including mobiles.

You could for example wire up a Double Click event on the Available Cars list, but I'm not sure that would work on mobile devices. You could wire up the Change event on the Available Cars so they get added with a simple item select, but this may not feel right (and be prone to wrong selections). If you're feeling really adventurous, you could implement a drag and drop scenario (you'd need to include the jQuery UI library), but again this may not feel very intuitive to your users.

Like I say, there are a few ways to do this, but personally I think that it's not really about what you CAN do, but what you SHOULD do.

Good luck with it.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
HTML

From novice to tech pro — start learning today.