4wk_
4wk_

Reputation: 2743

JS : display selections of a <select> multiple

I have this example :

<form action="form_action.asp">
  <select multiple="multiple" name="example" size="10">
    <option value="foo">Foo</option>
    <option value="bar">Bar</option>
    <option value="anything">Anything</option>
    <option value="else">Else</option>
  </select>
  <input type="submit" />
</form>

And I want to display how many lines are selected (by CTRL + clic). I think I can do it with a bit of JS, but I have no idea how to write it.

Any idea ?

Upvotes: 1

Views: 120

Answers (3)

PM5544
PM5544

Reputation: 720

Made an example: but the core is:

function parseSelected() {
    var count = 0;

    for ( var i = 0; i < length; i++ ) {
        if ( select[ i ].selected ) {
            count++
        }
    }
    output.innerHTML = count;
}

Upvotes: 0

Adam Rackis
Adam Rackis

Reputation: 83366

First give your select an id

<select id="yourSelect" multiple="multiple" name="example" size="10">

then

var numSelected = 0;
var allOptions = document.getElementById("yourSelect");
for (var i = 0; i < allOptions.length; i++)
    if (allOptions[i].selected)
        numSelected++

For completeness, I'll mention that if you ever want to use jQuery, and I'm not saying you should for something this simple, but if you ever do, you can do this with

var numSelected = $("option:selected", "#yourSelect").length;

Upvotes: 2

JesseBuesking
JesseBuesking

Reputation: 6596

I googled and found this article

var selected = new Array();
for (var i = 0; i < ob.options.length; i++) {
    if (ob.options[ i ].selected) {
        selected.push(ob.options[ i ].value);
    }
}

That will create an Array (selected) with the options. You can alter it easily to get the number of items selected.

Upvotes: 0

Related Questions