javascriptselectlistoneclick

Javascript multiple select


For a project I am working on, I need a multiple input list with a one click (de)selection, which work with the Internet Explorer (10). I found and modified this code, which is working very well:

But there is a problem:

The value of the selected options should be sent through the Post-Method to a PHP-script, but it sends only one selected value. After searching the web, I found out that I needed to name the NAME of my <select> like an array. So I changed NAME="sel_current" to NAME="sel_current[]". But with this change, this script stopped to work.

I hoped a change in document.forms[0].sel_current in init() to document.forms[0].sel_current[] would fix it, but it doesn't.

<HTML>
<HEAD>
    <TITLE>Multi-select test</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var multiSelect_current = new Object();
function storemultiSelect_current_current(obj) {
    var name = obj.name;
    multiSelect_current[name] = new Array();
    for (var i=0; i<obj.options.length; i++) {
        multiSelect_current[name][i] = obj.options[i].selected;
        }
    }
function changemultiSelect_current(obj) {
    var name = obj.name;
    for (var i=0; i<obj.options.length; i++) {
        if (obj.options[i].selected) {
            multiSelect_current[name][i] = !multiSelect_current[name][i];
            }
        obj.options[i].selected = multiSelect_current[name][i];
        }
    }
function init() {
    storemultiSelect_current_current(document.forms[0].sel_current);
    }

</SCRIPT>

</HEAD>
<BODY  onLoad="init()">
<FORM>
<SELECT NAME="sel_current" MULTIPLE METHOD="post" SIZE=10 onChange="changemultiSelect_current(this)">
    <OPTION value="1">1111</OPTION>
    <OPTION value="2" selected>2222</OPTION>
    <OPTION value="3">3333</OPTION>
    <OPTION value="4">4444</OPTION>
    <OPTION value="5" selected>5555</OPTION>
    <OPTION value="6">6666</OPTION>
    <OPTION value="7">7777</OPTION>
</SELECT>
</FORM>

</BODY>
</HTML>

Solution

  • You can use JSON.stringify(multiSelect_current[name]) finally, when sending to your server.

    In the function storemultiSelect_current_current's for loop, modify this : multiSelect_current[name][i][obj.options[i].innerText] = (obj.options[i].selected == true);

    screenshot :

    enter image description here