Thomas
Thomas

Reputation: 21631

How do I make a placeholder for a 'select' box?

I'm using placeholders for text inputs which is working out just fine. But I'd like to use a placeholder for my selectboxes as well. Of course I can just use this code:

<select>
    <option value="">Select your option</option>
    <option value="hurr">Durr</option>
</select>

But the 'Select your option' is in black instead of lightgrey. So my solution could possibly be CSS-based. jQuery is fine too.

This only makes the option grey in the dropdown (so after clicking the arrow):

option:first {
    color: #999;
}

The question is: How do people create placeholders in selectboxes? But it has already been answered, cheers.

And using this results in the selected value always being grey (even after selecting a real option):

select {
    color: #999;
}

Upvotes: 2083

Views: 2574198

Answers (30)

Jeff Chi 杰夫迟
Jeff Chi 杰夫迟

Reputation: 9

2025: A cool new way to colour the "placeholder" option using the modern :has() pseudo class.

<select>
    <option class="placeholder">Please select something</option>
    <option>Select me</option>
</select>
select:has(option.placeholder) {
    color: red;
}

Upvotes: 0

Hashan
Hashan

Reputation: 180

$('#id').select2({
        placeholder: "Select your option"
    });

Upvotes: -1

Dave Houlbrooke
Dave Houlbrooke

Reputation: 428

This is now possible with CSS only.

You can use the new :has() selector to activate placeholder styles on the select whenever an option with an empty value is selected.

This matches how text inputs show placeholders when they are empty.

<select>
  <option value="">Please choose...</option>
  <option value="a">Option 1</option>
  <option value="b">Option 2</option>
</select>
select {
  color: black;
}

select:has(option[value=""]:checked) {
  color: gray;
}

This select box will show Please choose... in gray, and will change to black when either of the other two options are selected.

This solution allows the Please choose... option to be reselected to clear the select and set its value to "" empty string.

In a required select box, you might also wish to hide the empty option from the list so it cannot be reselected:

select:required option[value=""] {
  display: none;
}

Edit: @Johnci points out some browsers need the black color reapplied to the options in the dropdown (because they inherit styles from the parent select box, and would otherwise sometimes be gray):

select option {
  color: black;
}

Upvotes: 17

Albireo
Albireo

Reputation: 11095

Something like this:

HTML:

<select id="choice">
    <option value="0" selected="selected">Choose...</option>
    <option value="1">Something</option>
    <option value="2">Something else</option>
    <option value="3">Another choice</option>
</select>

CSS:

#choice option { color: black; }
.empty { color: gray; }

JavaScript:

$("#choice").change(function () {
  if($(this).val() == "0") $(this).addClass("empty");
  else $(this).removeClass("empty")
});
    
$("#choice").change();

Working example: http://jsfiddle.net/Zmf6t/

Upvotes: 120

rramiii
rramiii

Reputation: 1186

Here is a good solution that worked for me:

HTML:

<select class="place_holder dropdown">
    <option selected="selected" style=" display: none;">Sort by</option>
    <option>two</option>
    <option>something</option>
    <option>4</option>
    <option>5</option>
</select>

CSS:

.place_holder {
    color: gray;
}
option {
    color: #000000;
}

JavaScript (jQuery):

jQuery(".dropdown").change(function () {
    jQuery(this).removeClass("place_holder");
});

After the customer makes the first select, there isn't any need for gray color, so the JavaScript code removes the class place_holder.

As a workaround for Internet Explorer, you can add the place_holder class again in case the first option is selected again.

Upvotes: 31

Dani-Br
Dani-Br

Reputation: 2457

The solution below works without any JavaScript:

option[default] {
  display: none;
}
<select>
  <option value="" default selected>Select Your Age</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>

It hides the default option once you've selected a different one, so you won't be able to re-select the default option afterward.

Upvotes: 56

William Isted
William Isted

Reputation: 12322

Here's what works in Firefox and Chrome (at least):

<style>
select:invalid { color: gray; }
</style>
<form>
<select required>
    <option value="" disabled selected hidden>Please Choose...</option>
    <option value="0">Open when powered (most valves do this)</option>
    <option value="1">Closed when powered, auto-opens when power is cut</option>
</select>
</form>

The disabled attribute stops the <option> from being selected with either mouse or keyboard; if you just used 'display:none', it allows the user to select it via keyboard navigation.

Using an empty value attribute on the "placeholder" option allows validation (via the required attribute) to work around having the "placeholder", so if the option isn't changed, but is required, the browser should prompt the user to choose an option from the list.

When the select element has the required attribute, it allows use of the :invalid CSS pseudo-class which allows you to style the select element when in its "placeholder" state. :invalid works here because of the empty value in the placeholder option.

Once a value has been set, the :invalid pseudo-class will be dropped. You can optionally also use :valid if you so wish.

This works best with custom styled select elements; in some cases i.e. (Mac in Chrome / Safari) you'll need to change the default appearance of the select box so that certain styles display, i.e., background-color and color. You can find some examples and more about compatibility at developer.mozilla.org.

Native element appearance Mac in Chrome:

Select box native Mac in Chrome

Using altered border element Mac in Chrome:

Altered select box Mac in Chrome

Upvotes: 1150

Paul K.
Paul K.

Reputation: 196

Solution for 2023 with :has selector:

select:has(option:disabled:checked[hidden]) {
  color: gray;
}

select option {
  color: black;
}
<select>
  <option selected disabled hidden>Choose</option>
  <option>One</option>
  <option>Two</option>
  <option>Three</option>
</select>

Upvotes: 9

Ali Muhammad Khowaja
Ali Muhammad Khowaja

Reputation: 435

There is Cool property in HTML and you can use it to create a Placeholder for select attribute In my case I am using following code and you can change it according to your requirements

 <select ref={relationship} required className="sellertype">
          <option value="" disabled selected hidden>Select Your Seller Type</option>
          <option value="1">Importer</option>
          <option value="2">Exporter</option>
          <option value="3">Local Seller</option>
          <option value="4">Local Buyer</option>
        </select>

Now "Select your Seller Type" will work as a placeholder

Upvotes: 12

David
David

Reputation: 42237

A non-CSS - no JavaScript/jQuery answer:

<label>Option name
<select>
    <option value="" disabled selected>Select your option</option>
    <option value="hurr">Durr</option>
</select>
</label>

Update (December 2021):

This works for latest Firefox, Chrome, and Safari. It used to not work for many browsers in the past, as pointed out in the comments.

Upvotes: 3793

Rmaxx
Rmaxx

Reputation: 1187

Ok,one that does the trick in my case, features (opposed to the accepted answer):

  • Grey if it's the placeholder
  • Selection is NOT required
  • Able to change back to greyed (value = "")
  • No external libraries (jquery etc)

It takes a small JS function to change it back grey/black if the value isnt "". The JS is explaned in the comments.. without comments only a few lines of code. By puting this in a function it will work for all checkboxes with this class..

function checkSelectboxes(){
    // select all checkboxes, here i choose to do so based on classname
    let selectboxes = document.querySelectorAll('.form-select'); 
    // loop through all checkboxes (only one this time)
    selectboxes.forEach(sb=>{   
      //add eventlistener to each checkbox
      sb.addEventListener('change',function(e){
      // if the value of this checkbox isnt "" Then add class, otherwise : remove it.
        e.target.value!=="" ? e.target.classList.add('changed') : e.target.classList.remove('changed');
      })
    })
  }
  
  //call the function
  checkSelectboxes();
.form-select{
  color:#ccc;
}
.form-select.changed{
  color:#000
}

.form-select option{
    color:#000;
}
.form-select option:first-of-type{
    color:#ccc;
}
<!-- give the first option an empty value , and set it as selected-->
<select type="text" class="form-select" >
  <option value="" selected>-- My placeholder --</option>
  <option>1 lorem --</option>
  <option>2 ipsum --</option>
  <option>3 dolor --</option>
</select>

Upvotes: -1

Kevin Glier
Kevin Glier

Reputation: 1386

Plain JavaScript solution that allows the user to reset the field by only disabling the option when no value is selected.

I didn't liked the way to just disable the option (even though it is indeed a very simple solution). But I had the requirement to reset the select box. So I created that plain JavaScript solution below.

All you have to do in the HTML code is the following:

<select name="animal">
    <option class="placeholder">Animal</option>
    <option value="1">Mouse</option>
    <option value="2">Cat</option>
</select>

To get this to work, just include following code in a script-block at the end of the HTML body.

(function () {
    const selectboxPlaceholderOptions = document.querySelectorAll('select option.placeholder');

    function selectBoxChange(event) {
        const select = event.srcElement;
        const placeholderOption = event.srcElement.querySelector('option.placeholder');
        if (!placeholderOption)
            return;

        if (!select.value || select.value === '') {
            placeholderOption.disabled = true;
            placeholderOption.textContent = placeholderOption.dataset['placeholderText'];
        } else {
            placeholderOption.disabled = false;
            placeholderOption.textContent = '';
        }
    }

    for (let i = 0; i < selectboxPlaceholderOptions.length; i++) {
        const option = selectboxPlaceholderOptions[i];
        const select = option.parentElement;

        option.value = '';
        option.disabled = true;
        option.dataset['placeholderText'] = option.textContent;
        select.addEventListener("change", selectBoxChange);
    }
})();

With the class placeholder assigned to the placeholder-option, everything is done. The JavaScript works with every select-box that is available until the end of page load.

Upvotes: -1

shreyasm-dev
shreyasm-dev

Reputation: 2834

You could set the first option's color to gray, set it's display to none, set the select's color to gray, and add an input event listener to it that sets it's color to black.

select > option:not(:first-of-type) {
  color: black;
}
<select style='color:gray' oninput='style.color="black"'>
  <option style='display:none'>
    Choose an option
  </option>
  <option>
    1
  </option>
  <option>
    2
  </option>
  <option>
    3
  </option>
</select>

Using the customElement API:

class placeholderSelect extends HTMLElement {
  connectedCallback() {
    this.innerHTML = `<select style='color:gray' oninput='style.color="black"'>
  <option style='display:none'>
    ${this.getAttribute('data-placeholder')}
  </option>
  ${this.innerHTML}
</select>`;

    Array.from(this.children[0].children).forEach(function(el, i) {
        el.style.color = 'black';
    });
  }
}

customElements.define('placeholder-select', placeholderSelect);
<placeholder-select data-placeholder='Choose an option'>
  <option>
    1
  </option>
  <option>
    2
  </option>
  <option>
    3
  </option>
</placeholder-select>

Upvotes: 9

Priya Maheshwari
Priya Maheshwari

Reputation: 483

  1. selected makes the particular option selected on page load
  2. disabled ensures the option is excluded in the form submission
  3. hidden visually hides the option in the dropdown list

    <select>
        <option selected disabled hidden>Choose an Option</option>
        <option>One</option>
        <option>Two</option>
        <option>Three</option>
</select>

Upvotes: 22

Abdulmajeed
Abdulmajeed

Reputation: 580

This works well for me:

<select class="form-control">
    <option value="" readonly="true" hidden="true" selected>Select your option</option>
    <option value="1">Something</option>
    <option value="2">Something else</option>
    <option value="3">Another choice</option>
</select>

Upvotes: 6

Will Wang
Will Wang

Reputation: 537

select:focus option.holder {
  display: none;
}
<select>
    <option selected="selected" class="holder">Please select</option>
    <option value="1">Option #1</option>
    <option value="2">Option #2</option>

</select>

Upvotes: 19

Aakash
Aakash

Reputation: 23825

This HTML + CSS solution worked for me:

form select:invalid {
  color: gray;
}

form select option:first-child {
  color: gray;
}

form select:invalid option:not(:first-child) {
  color: black;
}
<form>
  <select required>
    <option value="">Select Planet...</option>
    <option value="earth">Earth</option>
    <option value="pandora">Pandora</option>
  </select>
</form>

Upvotes: 11

PatrickReagan
PatrickReagan

Reputation: 624

Using the classnames package, here's a solution that worked with my React functional component. My component uses hooks, but that's probably not important to the solution. This approach is a functional riff off of the class based solution nicely described here... https://www.derpturkey.com/select-placeholder-with-react/

COMPONENT JS...

function NavBar(props, prevProps) {
            const ClassNames = require("classnames");  // package needs require rather than import
            const [where, changeWhere] = useState("");  // my component's value
            // classnames will add placeholderSelect class if chosen option's value is empty
            let whereClass = ClassNames("myOtherStyleRules", {
                placeholderSelect: !where,
            });
            ...
            return (
            ...
            <div id="where">
                            <select
                              className={whereClass}
                              value={where}
                              ...
                            >
                              <option value="" hidden> where? </option>    //  value must be empty, hidden from choice
                              <option value="24">Anchorage</option>
                              <option value="27">Birmingham</option>
                              <option value="28">Detroit</option>
                              <option value="25">Los Angeles</option>
                              <option value="26">Oahu</option>
                              <option value="29">Seattle</option>
                            </select>
                ... 

COMPONENT CSS...

        .placeholderSelect {
          color: rgb(167, 167, 167);
        }

Upvotes: -3

Thusitha Wickramasinghe
Thusitha Wickramasinghe

Reputation: 1103

You can do this without using JavaScript and using only HTML You need to set the default select option disabled="" and selected="" and select tag required="". Browsers don't allow the user to submit the form without selecting an option.

<form action="" method="POST">
    <select name="in-op" required="">
        <option disabled="" selected="">Select Option</option>
        <option>Option 1</option>
        <option>Option 2</option>
        <option>Option 3</option>
    </select>
    <input type="submit" value="Submit">
</form>

Upvotes: 5

Matthew Millar
Matthew Millar

Reputation: 132

Because of the diverse styling and functionality between answers provided in this thread, the table of below clarifies the styling and applicable form logic for each of the HTML, HTML+CSS and HTML+CSS+Javascript solutions provided.

I've had to use code formatting because tables aren't permitted in markup, for some reason.
A HTML table will be provided using the code snippet to work around the table restriction.

I've marked this post as community wiki so anyone can detail new posts, though please add JQuery, React, Angular, CoffeeScript, etc, to an alternate post to keep this table simple.

         | Technologies |                                                                Styling                                                                |
  Post   | CSS | Java-  | Select: Placeholder |  Select: valid option  |                  Option: placeholder                    |     Option: valid option     |
   ID    |     | script | Color |  Validation | Color |    Required    | Visibility | Selectable | Color |   Cond. formatting    | Color |   Cond. formatting   |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
41167307 | No  |   No   | Black |   Invalid   | Black |      Yes       |  Visible   |     No     | Grey  |          No           | Black |          No          |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
50200912 | No  |   No   | Black |    Valid    | Black |       No       | Invisible  |    N/A     |  N/A  |          No           | Black |          No          |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
5859221  | No  |   No   | Black |    Valid    | Black |       No       |  Visible   |     No     | Grey  |          No           | Black |          No          |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
38120777 | No  |   No   | Black |    Valid    | Black |       No       | Invisible  |    N/A     |  N/A  |          No           | Black |          No          |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
54860799 | Yes |   No   | Grey  |   Invalid   | Black |      Yes       | Invisible  |    N/A     |  N/A  |          No           | Black |          No          |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
52661024 | Yes |   No   | Grey  |   Invalid   | Black |      Yes       | Invisible  |    N/A     |  N/A  |          No           | Black | select:invalid{Grey} |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
8442831  | Yes |   No   | Grey  |   Invalid   | Black |      Yes       | Invisible  |    N/A     |  N/A  |          No           | Black | select:invalid{Grey} |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
29806043 | Yes |   No   | Grey  |   Invalid   | Black |      Yes       | Invisible  |    N/A     |  N/A  |          No           | Black |          No          |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
61966461 | Yes |   No   | Grey  |   Invalid   | Black |      Yes       | Invisible  |    N/A     |  N/A  | select:valid{visible} | Black |          No          |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
44406771 | Yes |   No   | Grey  |   Invalid   | Grey  |      No        |  Visible   |     No     | Grey  |          No           | Black | select:invalid{Grey} |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
40603035 | Yes |   No   | Black |    Valid    | Black |      No        | Invisible  |    N/A     |  N/A  |          No           | Black |          No          |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
22994211 | Yes |   No   | Grey  |    Valid    | Black |      No        | Invisible  |    N/A     |  N/A  |          No           | Black |          No          |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
21722343 | Yes |   No   | Grey  |    Valid    | Grey  |      No        | Invisible  |    N/A     |  N/A  |          No           | Black |          No          |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
48960650 | Yes |  Yes   | Grey  |   Invalid   | Black |      No        | Invisible  |    N/A     |  N/A  |          No           | Black |          No          |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
5805194  | Yes |  Yes   | Grey  |    Valid    | Black |      No        |  Visible   |    Yes     | Black |          No           | Black |          No          |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
50840409 | Yes |  Yes   | Grey  |    Valid    | Black |      Yes       |  Visible   |    Yes     | Grey  |          No           | Black |          No          |

Upvotes: 4

Jesto .K.J
Jesto .K.J

Reputation: 77

See this answer :

<select>
        <option style="display: none;" value="" selected>SelectType</option>
        <option value="1">Type 1</option>
        <option value="2">Type 2</option>
        <option value="3">Type 3</option>
        <option value="4">Type 4</option>
</select>

Upvotes: 3

Matthew Millar
Matthew Millar

Reputation: 132

Building upon MattW's answer, you can make the select placeholder option visible in the drop-down menu after a valid selection has been made, by conditionally hiding it only while the placeholder remains selected (and the select is therefore :invalid).

select:required:invalid {
  color: gray;
}
select:invalid > option[value=""][disabled] {
  display: none;
}
option {
  color: black;
}
<select required>
    <option value="" disabled selected>Select something...</option>
    <option value="1">One</option>
    <option value="2">Two</option>
</select>

Upvotes: 6

ksingh
ksingh

Reputation: 163

If you're reading this and using React, use defaultValue.

<option defaultValue>Select a country here</option>

Upvotes: 0

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48693

Based on Albireo's response, this version uses no jQuery and the CSS specificity is better.

const triggerEvent = (el, eventName) => {
  let event = document.createEvent('HTMLEvents')
  event.initEvent(eventName, true, false)
  el.dispatchEvent(event)
}

let select = document.querySelector('.placeholder-select')
select.addEventListener('change', (e) => {
  e.target.classList[e.target.value == 0 ? 'add' : 'remove']('empty')
})
triggerEvent(select, 'change')
.placeholder-select option {
  color: #000000;
}
.placeholder-select option:first-child {
  color: #444444;
  font-style: italic;
  font-weight: bold;
}
.placeholder-select.empty {
  color: #7F7F7F;
}
<select class="placeholder-select">
  <option value="0" selected="selected">Choose...</option>
  <option value="1">Something</option>
  <option value="2">Something else</option>
  <option value="3">Another choice</option>
</select>

Upvotes: -1

Jurik
Jurik

Reputation: 3264

You need form validation and modern browsers offer this from scratch.

So you do not need to take care that the user can not select the field. Because when he is doing it, the browser validation will tell him, that this is a wrong selection.

The browser built in validation function checkValidity().

Bootstrap has there a nice example as well.

HTML

<form class="needs-validation">
  <select required>
    <option value="">Please select an option</option>
    <option value="1">Foo</option>
    <option value="2">Bar</option>
  </select>
<form>

Javascript

form = document.getElementByClassName('needs-validation');
if(form.checkValidity() === true) {
  //form validation succeeded
} else {
  //form validation failed
}

Upvotes: 5

wlh
wlh

Reputation: 3525

I love the accepted solution, and it works great without JavaScript.

I just want to add how I adopted this answer for a controlled-select React Component, because it took me a few tries to figure it out. It would be really simple to incorporate react-select and be done with it, but unless you need the amazing functionality this repository provides, which I don't for the project in question, there is no need to add any more kilobytes to my bundle. Note, react-select handles placeholders in selects through a complex system of various inputs and html elements.

In React, for a controlled component, you cannot add the selected attribute to your options. React handles the state of the select via a value attribute upon the select itself, along with a change handler, where the value should match one of the value attributes within the options themselves.

Such as, for example

<select value={this.state.selectValue} onChange={this.handleChange} required={true}>
    {options}
</select>

Since it would be improper and in fact would throw an error to add the selected attribute to one of the options, what then?

The answer is simple once you think about it. Since we want our first option to be selected as well as disabled and hidden, we need to do three things:

  1. Add the hidden and disabled attribute to the first defined option.
  2. Set the value of the first option to be an empty string.
  3. Initialize the value of the select to also be an empty string.
state = { selectValue = "" } // State or props or their equivalent

// In the render function
<select value={this.state.selectValue} onChange={this.handleChange} required={true}>
    <option key="someKey" value="" disabled="disabled" hidden="hidden">Select from Below</option>
    {renderOptions()}
</select>

Now you can style the select as indicated above (or via a className if you prefer).

select:invalid { color: gray; }

Upvotes: 5

Jonathan Applebaum
Jonathan Applebaum

Reputation: 5986

Here is a working example how to achieve this with pure JavaScript that handles the options color after the first click:

<!DOCTYPE html>
<html>
  <head>
    <style>
      #myselect {
        color: gray;
      }
    </style>
  </head>

  <body>
    <select id="myselect">
      <option disabled selected>Choose Item
      </option>

      <option>Item 1
      </option>

      <option>Item 2
      </option>

      <option>Item 3
      </option>
    </select>

    <script>
      // Add event listener to change color in the first click
      document.getElementById("myselect").addEventListener("click", setColor)
      function setColor()
      {
        var combo = document.getElementById("myselect");
        combo.style.color = 'red';
        // Remove Event Listener after the color is changed at the first click
        combo.removeEventListener("click", setColor);
      }
    </script>
  </body>
</html>

Upvotes: -2

Roman Yakoviv
Roman Yakoviv

Reputation: 1724

The user should not see the placeholder in select options. I suggest to use the hidden attribute for the placeholder option, and you don't need the selected attribute for this option. You can just put it as the first.

select:not(:valid) {
  color: #999;
}
<select required>
    <option value="" hidden>Select your option</option>
    <option value="0">First option</option>
    <option value="1">Second option</option>
</select>

Upvotes: 25

arun kumar
arun kumar

Reputation: 1171

If you are using Angular, go like this:

<select>
    <option [ngValue]="undefined"  disabled selected>Select your option</option>
    <option [ngValue]="hurr">Durr</option>
</select>

Upvotes: 11

akinuri
akinuri

Reputation: 12027

I'm not content with HTML/CSS-only solutions, so I've decided to create a custom select using JavaScript.

This is something I've written in the past 30 mins, thus it can be further improved.

All you have to do is create a simple list with few data attributes. The code automatically turns the list into a selectable dropdown. It also adds a hidden input to hold the selected value, so it can be used in a form.

Input:

<ul class="select" data-placeholder="Role" data-name="role">
  <li data-value="admin">Administrator</li>
  <li data-value="mod">Moderator</li>
  <li data-value="user">User</li>
</ul>

Output:

<div class="ul-select-container">
    <input type="hidden" name="role" class="hidden">
    <div class="selected placeholder">
        <span class="text">Role</span>
        <span class="icon">▼</span>
    </div>
    <ul class="select" data-placeholder="Role" data-name="role">
        <li class="placeholder">Role</li>
        <li data-value="admin">Administrator</li>
        <li data-value="mod">Moderator</li>
        <li data-value="user">User</li>
    </ul>
</div>

The text of the item that's supposed to be a placeholder is grayed out. The placeholder is selectable, in case the user wants to revert his/her choice. Also using CSS, all the drawbacks of select can be overcome (e.g., inability of the styling of the options).

// Helper function to create elements faster/easier
// https://github.com/akinuri/js-lib/blob/master/element.js
var elem = function(tagName, attributes, children, isHTML) {
  let parent;
  if (typeof tagName == "string") {
    parent = document.createElement(tagName);
  } else if (tagName instanceof HTMLElement) {
    parent = tagName;
  }
  if (attributes) {
    for (let attribute in attributes) {
      parent.setAttribute(attribute, attributes[attribute]);
    }
  }
  var isHTML = isHTML || null;
  if (children || children == 0) {
    elem.append(parent, children, isHTML);
  }
  return parent;
};
elem.append = function(parent, children, isHTML) {
  if (parent instanceof HTMLTextAreaElement || parent instanceof HTMLInputElement) {
    if (children instanceof Text || typeof children == "string" || typeof children == "number") {
      parent.value = children;
    } else if (children instanceof Array) {
      children.forEach(function(child) {
        elem.append(parent, child);
      });
    } else if (typeof children == "function") {
      elem.append(parent, children());
    }
  } else {
    if (children instanceof HTMLElement || children instanceof Text) {
      parent.appendChild(children);
    } else if (typeof children == "string" || typeof children == "number") {
      if (isHTML) {
        parent.innerHTML += children;
      } else {
        parent.appendChild(document.createTextNode(children));
      }
    } else if (children instanceof Array) {
      children.forEach(function(child) {
        elem.append(parent, child);
      });
    } else if (typeof children == "function") {
      elem.append(parent, children());
    }
  }
};


// Initialize all selects on the page
$("ul.select").each(function() {
  var parent    = this.parentElement;
  var refElem   = this.nextElementSibling;
  var container = elem("div", {"class": "ul-select-container"});
  var hidden    = elem("input", {"type": "hidden", "name": this.dataset.name, "class": "hidden"});
  var selected  = elem("div", {"class": "selected placeholder"}, [
    elem("span", {"class": "text"}, this.dataset.placeholder),
    elem("span", {"class": "icon"}, "&#9660;", true),
  ]);
  var placeholder = elem("li", {"class": "placeholder"}, this.dataset.placeholder);
  this.insertBefore(placeholder, this.children[0]);
  container.appendChild(hidden);
  container.appendChild(selected);
  container.appendChild(this);
  parent.insertBefore(container, refElem);
});

// Update necessary elements with the selected option
$(".ul-select-container ul li").on("click", function() {
  var text     = this.innerText;
  var value    = this.dataset.value || "";
  var selected = this.parentElement.previousElementSibling;
  var hidden   = selected.previousElementSibling;
  hidden.value = selected.dataset.value = value;
  selected.children[0].innerText = text;
  if (this.classList.contains("placeholder")) {
    selected.classList.add("placeholder");
  } else {
    selected.classList.remove("placeholder");
  }
  selected.parentElement.classList.remove("visible");
});

// Open select dropdown
$(".ul-select-container .selected").on("click", function() {
  if (this.parentElement.classList.contains("visible")) {
    this.parentElement.classList.remove("visible");
  } else {
    this.parentElement.classList.add("visible");
  }
});

// Close select when focus is lost
$(document).on("click", function(e) {
  var container = $(e.target).closest(".ul-select-container");
  if (container.length == 0) {
    $(".ul-select-container.visible").removeClass("visible");
  }
});
.ul-select-container {
  width: 200px;
  display: table;
  position: relative;
  margin: 1em 0;
}
.ul-select-container.visible ul {
  display: block;
  padding: 0;
  list-style: none;
  margin: 0;
}
.ul-select-container ul {
  background-color: white;
  border: 1px solid hsla(0, 0%, 60%);
  border-top: none;
  -webkit-user-select: none;
  display: none;
  position: absolute;
  width: 100%;
  z-index: 999;
}
.ul-select-container ul li {
  padding: 2px 5px;
}
.ul-select-container ul li.placeholder {
  opacity: 0.5;
}
.ul-select-container ul li:hover {
  background-color: dodgerblue;
  color: white;
}
.ul-select-container ul li.placeholder:hover {
  background-color: rgba(0, 0, 0, .1);
  color: initial;
}
.ul-select-container .selected {
  background-color: white;
  padding: 3px 10px 4px;
  padding: 2px 5px;
  border: 1px solid hsla(0, 0%, 60%);
  -webkit-user-select: none;
}
.ul-select-container .selected {
  display: flex;
  justify-content: space-between;
}
.ul-select-container .selected.placeholder .text {
  color: rgba(0, 0, 0, .5);
}
.ul-select-container .selected .icon {
  font-size: .7em;
  display: flex;
  align-items: center;
  opacity: 0.8;
}
.ul-select-container:hover .selected {
  border: 1px solid hsla(0, 0%, 30%);
}
.ul-select-container:hover .selected .icon {
  opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="select" data-placeholder="Role" data-name="role">
  <li data-value="admin">Administrator</li>
  <li data-value="mod">Moderator</li>
  <li data-value="user">User</li>
</ul>

<ul class="select" data-placeholder="Sex" data-name="sex">
  <li data-value="male">Male</li>
  <li data-value="female">Female</li>
</ul>


Update: I've improved this (selection using up/down/enter keys), tidied up the output a little bit, and turned this into a object. Current output:

<div class="li-select-container">
    <input type="text" readonly="" placeholder="Role" title="Role">
    <span class="arrow">▼</span>
    <ul class="select">
        <li class="placeholder">Role</li>
        <li data-value="admin">Administrator</li>
        <li data-value="mod">Moderator</li>
        <li data-value="user">User</li>
    </ul>
</div>

Initialization:

new Liselect(document.getElementsByTagName("ul")[0]);

For further examination: JSFiddle, GitHub (renamed).


Update: I am have rewritten this again. Instead of using a list, we can just use a select. This way it'll work even without JavaScript (in case it's disabled).

Input:

<select name="role" data-placeholder="Role" required title="Role">
    <option value="admin">Administrator</option>
    <option value="mod">Moderator</option>
    <option>User</option>
</select>

new Advancelect(document.getElementsByTagName("select")[0]);

Output:

<div class="advanced-select">
    <input type="text" readonly="" placeholder="Role" title="Role" required="" name="role">
    <span class="arrow">▼</span>
    <ul>
        <li class="placeholder">Role</li>
        <li data-value="admin">Administrator</li>
        <li data-value="mod">Moderator</li>
        <li>User</li>
    </ul>
</div>

JSFiddle, GitHub.

Upvotes: 5

Related Questions