uccblack uccblack - 4 months ago 59
Javascript Question

React cannot choose from select multiple form

So I'm making a

select multiple
form in React.js, yet every time options are generated, I cannot select the options. If I click on an option, it is instantly unhighlighted and not selected.

React.DOM.div({
className: 'form-group'
}, React.DOM.select({
multiple: true,
name: 'team_players',
value: this.state.team_players,
onChange: this.handleArrayChange
}, React.DOM.option({
value: '',
disabled: true
}, 'Select Players'), (function() {
var i, len, ref, results;
ref = this.state.players;
results = [];
for (i = 0, len = ref.length; i < len; i++) {
player = ref[i];
results.push(React.DOM.option({
key: player.id,
value: player.detail.inputs["NAME"]
}, player.detail.inputs["NAME"]));
}
return results;
}).call(this)));


*Please note that this is the js version generated through js2.coffee from my coffeescript version which goes as such: *

React.DOM.div
className: 'form-group'
React.DOM.select
multiple: true
name: 'team_players'
value: @state.team_players
onChange: @handleArrayChange
React.DOM.option
value: ''
disabled: true
'Select Players'
for player in @state.players
React.DOM.option
key: player.id
value: player.detail.inputs["NAME"]
player.detail.inputs["NAME"]


My handleArrayChange function goes as such:

({
handleArrayChange: function(e) {
var i, len, name, obj, option, options, team_array;
options = e.target.options;
name = e.target.name;
team_array = [];
for (i = 0, len = options.length; i < len; i++) {
option = options[i];
team_array.push(option);
}
return this.setState((
obj = {},
obj["" + name] = team_array,
obj
));
}
});


and in its coffescript form:

handleArraychange: (e) ->
options = e.target.options
name = e.target.name
team_array = []
for option in options
team_array.push option
@setState "#{name}": team_array


Why does this form not handle my inputs properly?

Answer

You're setting the team_array state as an array of option HTML elements, not an array of strings. Try this instead:

handleArraychange: (e) ->
  options = e.target.options
  name = e.target.name
  team_array = []
  for option in options 
    team_array.push option.value
  @setState "#{name}": team_array
Comments