Drop Down Menu/Text Field in one
Asked Answered
T

9

107

I'm working on building new site, and I need a drop down menu to select the amount of something in my site. But at the same time I need this drop down list to accept text. So if the client wants to choose from the drop down list then he can, also if the client want to enter the amount by text then he can also. As you can see I want to make it dual.

For example: suppose there is an amount drop down menu, and its elements are (1,2,3);

Suppose now that the client needs the amount to be 5 - this is his right - it does not exist in the drop down list, so the client now must enter the amount textually. So for any entry the client must either choose from the drop down list or enter the amount textually.

After the description of my problem, and the simple example that I have introduced to you, here is my question:

Is there HTML code to make a drop down menu and a text field in one, as dual, not separated?

Tophus answered 19/8, 2013 at 8:6 Comment(2)
Possible duplicate of HTML select drop-down with an input fieldApices
Possible duplicate of HTML select form with option to enter custom valueSpooner
M
49

Option 1

Include the script from dhtmlgoodies and initialize like this:

<input type="text" name="myText" value="Norway"
       selectBoxOptions="Canada;Denmark;Finland;Germany;Mexico"> 
createEditableSelect(document.forms[0].myText);

Option 2

Here's a custom solution which combines a <select> element and <input> element, styles them, and toggles back and forth via JavaScript

<div style="position:relative;width:200px;height:25px;border:0;padding:0;margin:0;">
  <select style="position:absolute;top:0px;left:0px;width:200px; height:25px;line-height:20px;margin:0;padding:0;"
          onchange="document.getElementById('displayValue').value=this.options[this.selectedIndex].text; document.getElementById('idValue').value=this.options[this.selectedIndex].value;">
    <option></option>
    <option value="one">one</option>
    <option value="two">two</option>
    <option value="three">three</option>
  </select>
  <input type="text" name="displayValue" id="displayValue" 
         placeholder="add/select a value" onfocus="this.select()"
         style="position:absolute;top:0px;left:0px;width:183px;width:180px\9;#width:180px;height:23px; height:21px\9;#height:18px;border:1px solid #556;"  >
  <input name="idValue" id="idValue" type="hidden">
</div>
Moritz answered 19/8, 2013 at 8:10 Comment(2)
fixing the height and color will give you: jsfiddle.net/aljohnix/78mdmrs7Beef
Thanks, I used this solution, with a few other tweaks I'd recommend. First, on change to the input box, reset the select value to the empty string option. Otherwise if you select an option and then edit it, you can't reset to that option because it's already selected in the drop-down even though the value no longer matches. Secondly, and this was just an issue of making it look nice with the other styling on my page that highlights the current input, on focus for the select set focus to the input. Drop down still works, but the focus highlighting looks right.Savage
T
201

You can do this natively with HTML5 <datalist>:

<label>Choose a browser from this list:
<input list="browsers" name="myBrowser" /></label>
<datalist id="browsers">
  <option value="Chrome">
  <option value="Firefox">
  <option value="Internet Explorer">
  <option value="Opera">
  <option value="Safari">
  <option value="Microsoft Edge">
</datalist>
Telega answered 24/6, 2015 at 1:44 Comment(12)
Their behaviour seems to vary across browsers. In Firefox (40.0.3), I see the suggestions 'label1' and 'label2', while in Chrome (45.0.2454.85 m) I see the suggestions 'value1' and 'value2'. They also work in subtly different ways, e.g. in their responses to focus/mouseover, and Chrome displays the labels by the values.Predispose
If I remove the label= attributes, Firefox will suggest the values, like Chrome. (Chrome will never suggest the labels - if I remove the 'value=' attribute, Chrome shows nothing.)Predispose
IE11 shows the labels if both are present, counterintiuitively shows nothing if only labels are present, and values if values are present. So of IE, Firefox and Chrome, the only consistent behaviour is that you will get a list of values if you include only values without labels.Predispose
I wonder if some of the compatibility problems have to do with the options tags in this particular example not using a closing tag or closing slash? ex: <option label='label1' value='value1' /> Just a thought.Transmundane
Another issue I've seen with the HTML5 entity that the accepted answer solves is that (at least in Chrome where I tested it) the drop down list of values filters down to just those options that match the text that is typed. For my application at least, I still want to be able to see the full list of options even when some text has been entered. I was using the HTML5 entity, but to fix this problem, I'm going to switch the the javascript solution.Savage
As for the label vs. value behavior, this makes some sense if you think about it. A select list can have a value it shows which is different than the value it submits, but with a text box, what you see is what you get. So, what do you expect to happen if you pick from a list to fill a text box? You want the drop down to show "label1" but then put "value1" in the box when selected? This doesn't make sense. What the list shows is what goes in the box. So, you don't need separate labels and values. If you use both for browser compatibility you should still use the same text for both.Savage
Also, the list creates a block of "whitespace" where the items in the list might appear if they were visible (Firefox 58 - others not tested). Completely messes up all the CSS. Not recommended.Harelip
Still, in 2019, the support for this doesn't seem very widespread: caniuse.com/#search=datalistCorbin
I see some issue with this in chrome, When dropdown shows and you scroll the page, the dropdown moves along with the page. But in other browsers, when you scroll page the dropdown gets closed. Anyone knows how to fix this in chrome?Desinence
How to set the default value? Like <option value="blaah" selected>Mercury
@Telega how can I select multiple values with datalist do it have multiple attribute like selectNichy
This is very easy to implement, one small issue, I want the user to use the dropdown tool way more than the input tool, this implies that you're supposed to search, rather than dropdown and occasionally type your custom value.Toady
M
49

Option 1

Include the script from dhtmlgoodies and initialize like this:

<input type="text" name="myText" value="Norway"
       selectBoxOptions="Canada;Denmark;Finland;Germany;Mexico"> 
createEditableSelect(document.forms[0].myText);

Option 2

Here's a custom solution which combines a <select> element and <input> element, styles them, and toggles back and forth via JavaScript

<div style="position:relative;width:200px;height:25px;border:0;padding:0;margin:0;">
  <select style="position:absolute;top:0px;left:0px;width:200px; height:25px;line-height:20px;margin:0;padding:0;"
          onchange="document.getElementById('displayValue').value=this.options[this.selectedIndex].text; document.getElementById('idValue').value=this.options[this.selectedIndex].value;">
    <option></option>
    <option value="one">one</option>
    <option value="two">two</option>
    <option value="three">three</option>
  </select>
  <input type="text" name="displayValue" id="displayValue" 
         placeholder="add/select a value" onfocus="this.select()"
         style="position:absolute;top:0px;left:0px;width:183px;width:180px\9;#width:180px;height:23px; height:21px\9;#height:18px;border:1px solid #556;"  >
  <input name="idValue" id="idValue" type="hidden">
</div>
Moritz answered 19/8, 2013 at 8:10 Comment(2)
fixing the height and color will give you: jsfiddle.net/aljohnix/78mdmrs7Beef
Thanks, I used this solution, with a few other tweaks I'd recommend. First, on change to the input box, reset the select value to the empty string option. Otherwise if you select an option and then edit it, you can't reset to that option because it's already selected in the drop-down even though the value no longer matches. Secondly, and this was just an issue of making it look nice with the other styling on my page that highlights the current input, on focus for the select set focus to the input. Drop down still works, but the focus highlighting looks right.Savage
R
13

The modern solution is an input field of type "search"!

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/search https://www.w3schools.com/tags/tag_datalist.asp

Somewhere in your HTML you define a datalist for later reference:

<datalist id="mylist">
   <option value="Option 1">
   <option value="Option 2">
   <option value="Option 3">
</datalist>

Then you can define your search input like this:

<input type="search" list="mylist">

Voilà. Very nice and easy.

Requisite answered 9/2, 2020 at 16:37 Comment(5)
Good answer, but it's not the input field type that is important.Naval
@Naval Yes it is, because it is of type "search", so that you can do both - choose a value from the list or type a value and it will search in the list.Requisite
“These are functionally identical to text inputs, but may be styled differently by the user agent.” - from your first link.Naval
@Naval I'm not sure what they mean by "functionally identical to text inputs". Text inputs don't usually have datalists added.Requisite
This answer seems pretty much identical to onaclov2000's - but with this one, you can use a search, which doesn't seem to be possible without the "type='search'" specification.Requisite
B
7

You can use the <datalist> tag instead of the <select> tag.

<input list="browsers" name="browser" id="browser">
<datalist id="browsers">
  <option value="Edge">
  <option value="Firefox">
  <option value="Chrome">
  <option value="Opera">
  <option value="Safari">
</datalist>
Brigidabrigit answered 24/6, 2020 at 16:12 Comment(0)
S
5

I found this question and discussion very helpful and wanted to show the solution I ended up with. It is based on the answer given by @DevangRathod, but I used jQuery and made a couple tweaks to it, so wanted to show a fully commented sample to help anyone else working on something similar. I originally had been using the HTML5 data-list element, but was dissatisfied with that solution since it removes options from the drop down list that don't match text typed in the box. In my application, I wanted the full list to always be available.

Fully functional demo here: https://jsfiddle.net/abru77mm/

HTML:

<!-- 
Most style elements I left to the CSS file, but some are here.
Reason being that I am actually calculating my width dynamically
in my application so when I dynamically formulate this HTML, I
want the width and all the factors (such as padding and border
width and margin) that go into determining the proper widths to
be controlled by one piece of code, so those pieces are done in
the in-line style.  Otherwise I leave the styling to the CSS file.
-->
<div class="data-list-input" style="width:190px;">
  <select class="data-list-input" style="width:190px;">
    <option value="">&lt;Free Form Text&gt;</option>
    <option value="Male">Male</option>
    <option value="Female">Female</option>
    <!-- Note that though the select/option allows for a different
    display and internal value, there is no such distinction in the
    text box, so for all the options (except the "none" option) the
    value and content of the option should be identical. -->
  </select>
  <input class="data-list-input" style="width:160px;padding:4px 6px;border-width:1px;margin:0;" type="text" name="sex" required="required" value="">
</div>

JS:

jQuery(function() {
  //keep the focus on the input box so that the highlighting
  //I'm using doesn't give away the hidden select box to the user
  $('select.data-list-input').focus(function() {
    $(this).siblings('input.data-list-input').focus();
  });
  //when selecting from the select box, put the value in the input box
  $('select.data-list-input').change(function() {
    $(this).siblings('input.data-list-input').val($(this).val());
  });
  //When editing the input box, reset the select box setting to "free
  //form input". This is important to do so that you can reselect the
  //option you had selected if you want to.
  $('input.data-list-input').change(function() {
    $(this).siblings('select.data-list-input').val('');
  });
});

CSS:

div.data-list-input
{
    position: relative;
    height: 20px;
    display: inline-flex;
    padding: 5px 0 5px 0;
}
select.data-list-input
{
    position: absolute;
    top: 5px;
    left: 0px;
    height: 20px;
}
input.data-list-input
{
    position: absolute;
    top: 0px;
    left: 0px;
    height: 20px;
}

Any comments for improvement on my implementation welcome. Hope someone finds this helpful.

Savage answered 5/7, 2016 at 5:3 Comment(2)
How to restrict the user from typing? when user clicks the textbox, show the dropdown valuesVanatta
@Vanatta That's not really the point of this approach. If you don't want the user to type, then just use a standard drop down list by itself. The point of the solution is specifically for when you want to allow the user to type in their own value.Savage
O
2

I'd like to add a jQuery autocomplete based solution that does the job.

Step 1: Make the list fixed height and scrollable

Get the code from https://jqueryui.com/autocomplete/ "Scrollable" example, setting max height to the list of results so it behaves as a select box.

Step 2: Open the list on focus:

Display jquery ui auto-complete list on focus event

Step 3: Set minimum chars to 0 so it opens no matter how many chars are in the input

Final result:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Scrollable results</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <style>
  .ui-autocomplete {
    max-height: 100px;
    overflow-y: auto;
    /* prevent horizontal scrollbar */
    overflow-x: hidden;
  }
  /* IE 6 doesn't support max-height
   * we use height instead, but this forces the menu to always be this tall
   */
  * html .ui-autocomplete {
    height: 100px;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
//      source: availableTags, // uncomment this and comment the following to have normal autocomplete behavior
      source: function (request, response) {
          response( availableTags);
      },
      minLength: 0
    }).focus(function(){
//        $(this).data("uiAutocomplete").search($(this).val()); // uncomment this and comment the following to have autocomplete behavior when opening
        $(this).data("uiAutocomplete").search('');
    });
  } );
  </script>
</head>
<body>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>


</body>
</html>

Check jsfiddle here:

https://jsfiddle.net/bao7fhm3/1/

Osber answered 17/8, 2018 at 15:55 Comment(0)
U
1

I like jQuery Token input. Actually prefer the UI over some of the other options mentioned above.

http://loopj.com/jquery-tokeninput/

Also see: http://railscasts.com/episodes/258-token-fields for an explanation

Underdrawers answered 8/2, 2016 at 19:50 Comment(1)
Does this plugin support arbitrary (user selectable) “tokens”? At least the demos don’t suggest that: whenever I type something which is not available in the pre-defined choices, my text is automatically removed when the text field loses focus.Aroid
P
1

Inspired by the js fiddle by @ajdeguzman (made my day), here is my node/React derivative:

 <div style={{position:"relative",width:"200px",height:"25px",border:0,
              padding:0,margin:0}}>
    <select style={{position:"absolute",top:"0px",left:"0px",
                    width:"200px",height:"25px",lineHeight:"20px",
                    margin:0,padding:0}} onChange={this.onMenuSelect}>
            <option></option>
            <option value="starttime">Filter by Start Time</option>
            <option value="user"     >Filter by User</option>
            <option value="buildid"  >Filter by Build Id</option>
            <option value="invoker"  >Filter by Invoker</option>
    </select>
    <input name="displayValue" id="displayValue" 
           style={{position:"absolute",top:"2px",left:"3px",width:"180px",
                   height:"21px",border:"1px solid #A9A9A9"}}
           onfocus={this.select} type="text" onChange={this.onIdFilterChange}
           onMouseDown={this.onMouseDown} onMouseUp={this.onMouseUp} 
           placeholder="Filter by Build ID"/>
 </div>

Looks like this:

enter image description here

Phrenology answered 5/3, 2018 at 14:10 Comment(0)
O
0

You can use TextField as dropdown select ... try this code

var data = ['apple','orange','banana','pineapple'] 

             <TextField                     
                  select
                  size="small"
                  fullWidth                  
                  SelectProps={{ MenuProps: { sx: { maxHeight: 247 } } }}                
                >
                  {data.map((text) => (
                    <MenuItem value={text}>{text}</MenuItem>
                  ))}
                </TextField>
Outlawry answered 28/2, 2022 at 9:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.