2

I have a HTML Select Dropdown in a form which asks the user to pick a question out of some pre-selected security questions. (Such as "What's your favorite City", "What's the color of your car" etc.)

How can I add another option to the list such as "Write your own" and when user selects it, a new Input box is shown for the user to write his/her own question.

One strategy I can think of is to create an input element with an ng-show to hide/show it based on the value of the Select. Is there a better way to do it?

1
  • That sounds pretty reasonable to me Commented Oct 30, 2015 at 21:34

2 Answers 2

2

There is a completely JS-free possibility found here: HTML combo box with option to type an entry which will likely require you to use the ng-options directive in the <select> tag.

However, if you prefer to stick with your imported library(ies), you can start by injecting a text input box into your last option:

  <select ng-model="selectedItem">
    <option ng-repeat="item in items" value="{{item}}">{{item}}</option>
    <option ng-blur="addItem()"><input type="text" placeholder="Write your own" id="newItem"></option>
  </select>

Then you define the ng-blur function to add the new item to the list of items in your array of items:

  addItem = function () {
      $scope.items[] = document.getElementById("newItem").value;
  }

Your variable names may vary, but this is the basic process I would use if I had the need. There may also be a better (Angular) directive or function that would work better for getting the value of your injected text box (possibly by name or parent-child relationships).

Hope this points you in the right direction.

Thanks,

Chris

Sign up to request clarification or add additional context in comments.

Comments

1

Your best bet is probably to write a custom directive that will simulate a select box (likely using styled radio buttons), but add an extra option in there that is an input. I've done something similar for several projects and thought it isn't particularly difficult, but there is a lot to consider (including accessibility and keyboard controls).

Or you can find one of the many open-source directives online. While it might not be exactly what you're looking for UI-Select might be a good option.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.