简体   繁体   中英

Select from dropdown in Meteor when only one value exists

I'm trying to select one value from a dropdown in meteor.

It should still be selectable even if it is the only one, as I have a click event based on it. ie

'click option[data-action="doSomething"]': function(event, template){
    event.preventDefault();
    console.log('Pressed');
    //Do something here.
  }

and the HTML looks like:

{{#each something}}
<option data-action="doSomething" {{setSelected}}>{{nickname}}</option>
{{/each}}

When I try select, this all works but only when there is more than 1 value to select from.

Does anyone know how to select when only 1 value exists? Using click option .

The "click" event won't work for you consistently on <option> elements. Use the "change" event on the <select> element itself instead. Then you can access the <option> element's value from the event handler and apply logic from there.

Events

'change .actionSelect': function(event, template){
  const selectElem = event.currentTarget;

  switch(selectElem.value)
  {
    case 'action1': 
      // Do a thing
      break;
    case 'action2': 
      // Do a different thing
      break;
  }
}

Template

<select class="actionSelect">
  {{#each thing in something}}
    <option value="{{thing.action}}" selected="{{thing.setSelected}}">{{thing.nickname}}</option>
  {{/each}}
</select>

Note: I used the "each...in" loop here as it is a best practice. Keeps template-level variables from becoming inaccessible within loops.

As HMR mentioned in the comments, you might also want to add a default <option disabled> element so that you can ensure that the user is prompted to select something "new" when there is only one option.

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