Hardy Thiergart
Hardy Thiergart

Reputation: 1

Assign Multiselect Drop-down Options to a String Variable in Javascript

I would like to store a couple of options from a HTML multiselect Drop-down function to another variable in Javascript.

<form name="myedit" id="myedit" action="next.php" method="post" onsubmit="return copyLongDesc( 'oxarticles__oxlongdesc' );"
   <select id="Project" name="Data" size="10" multiple="multiple" onchange="rewrite_data();">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
    </select>
</form>

It has to be stored in this string variable 'editval[oxarticles__oxmerkmaleaa]' with any change Event. The variable is already in the formular from this script.

I need to know how I get that to work ?

I would appreciate your help.

Upvotes: 0

Views: 827

Answers (1)

loelsonk
loelsonk

Reputation: 3596

We create an event listener change and pass a function to it. See it in action, working example.

var select = document.getElementById('Project');

function selectedOptions() { 
  var result = [];
  var options = this.options;

  for (i = 0; i < options.length; i++) {
    var option = options[i];

    if (option.selected) {
      result.push(option.value);
    }
  }
  
  console.log(result);
  return result;
}

select.addEventListener('change', selectedOptions);
<select id="Project" name="Data" size="10" multiple="multiple" >
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
    </select>

Upvotes: 0

Related Questions