简体   繁体   中英

How to handle a select with multiple items when only one item is selected

I have a select form element and it accepts multiple items.

When the form is submitted I'm adding the items into an array to then handle them then running through the array to perform an action on each item.

I'm coming across a problem when only one item is selected.

The length of the array when one item is passed through is not 1 it's the number of characters in the item that is selected.

function processForm(formObject){
  var list = [];
  list = formObject.listElement;

  for (var i=0;i<list.length;i++) {
    Logger.log(list[i]);
  }
}

The above would log each item if more than one item is selected in the form. If only one is selected the length is the number of character in that one item. How can I resolve this so if only one item is selected we treat this as an array with one item?

You have:

var list = [];

which assigns an empty array to list , then:

list = formObject.listElement

replaces it with whatever is returned by formObject.listElement , so the initial assignment is pointless.

You haven't indicated what type of control listElement is, it may be a Class MultipleChoiceItem or Class ListItem . Both have a getChoices method that returns an array of the choices.

If you use that method, there should be no need to test whether the return value is an array or not, it should always be a (possibly empty) array:

list = formObject.listElement.getChoices();

assuming that listElement is one of the above objects.

Iterating through a string as if it were an array would give the behavior you describe. You can convert an array first, if it's not already one

var list = formObject.listElement;
if (!Array.isArray(list)) list = [list];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM