How do I make a placeholder for a 'select'

2018-12-31 03:08发布

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. Ofcourse 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;
}

Edit: 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;
}

23条回答
明月照影归
2楼-- · 2018-12-31 03:35

I just added hidden attribute in option like below, It is working fine for me.

<select>
  <option hidden>Sex</option>
  <option>Male</option>
  <option>Female</option>
</select>

查看更多
千与千寻千般痛.
3楼-- · 2018-12-31 03:35

Here's my contribution. HAML + Coffeescript + SCSS

HAML
=f.collection_select :country_id, [us] + Country.all, :id, :name, {prompt: t('user.country')}, class: 'form-control'
Coffeescript
  $('select').on 'change', ->
    if $(this).val()
      $(this).css('color', 'black')
    else
      $(this).css('color', 'gray')
  $('select').change()
SCSS
select option {
  color: black;
}

It's possible to use only CSS by changing the server code and only setting the class styles depending on the current value of the property, but this way seems easier and cleaner.

$('select').on('change', function() {
  if ($(this).val()) {
    return $(this).css('color', 'black');
  } else {
    return $(this).css('color', 'gray');
  }
});

$('select').change();
    select option {
      color: black;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" name="user[country_id]" id="user_country_id">
  <option value="">Country</option>
                      <option value="231">United States</option>
                      <option value="1">Andorra</option>
                      <option value="2">Afghanistan</option>
                      <option value="248">Zimbabwe</option></select>

You can add more CSS (select option:first-child) to keep the placeholder gray when it opens, but I didn't care about that.

查看更多
浮光初槿花落
4楼-- · 2018-12-31 03:38

Here is a CSS solution that works beautifully. The content is added (and absolutely positioned relative to the container) after the containing element (via :after pseudo-class). It gets its text from the placeholder attribute that I defined where I used the directive (attr(placeholder)). Another key factor is pointer-events: none - this allows clicks on the placeholder text to pass through to the select. Otherwise it won't drop down if the user clicks the text.

I add the .empty class myself in my select directive but normally I find that angular adds/removes .ng-empty for me (I assume it's b/c I'm injecting version 1.2 of Angular in my code sample)

(The sample also demonstrates how to wrap HTML elements in angularJS to create your own custom inputs)

var app = angular.module("soDemo", []);
app.controller("soDemoController", function($scope) {
  var vm = {};
  vm.names = [{
      id: 1,
      name: 'Jon'
    },
    {
      id: 2,
      name: 'Joe'
    }, {
      id: 3,
      name: 'Bob'
    }, {
      id: 4,
      name: 'Jane'
    }
  ];
  vm.nameId;
  $scope.vm = vm;
});

app.directive('soSelect', function soSelect() {
  var directive = {
    restrict: 'E',
    require: 'ngModel',
    scope: {
      'valueProperty': '@',
      'displayProperty': '@',
      'modelProperty': '=',
      'source': '=',
    },
    link: link,
    template: getTemplate
  };
  return directive;

  /////////////////////////////////
  function link(scope, element, attrs, ngModelController) {
    init();
    return;

    ///////////// IMPLEMENTATION

    function init() {
      initDataBinding();
    }

    function initDataBinding() {
      ngModelController.$render = function() {
        if (scope.model === ngModelController.$viewValue) return;
        scope.model = ngModelController.$viewValue;
      }

      scope.$watch('model', function(newValue) {
        if (newValue === undefined) {
          element.addClass('empty');
          return;
        }
        element.removeClass('empty');
        ngModelController.$setViewValue(newValue);
      });
    }
  }

  function getTemplate(element, attrs) {
    var attributes = [
      'ng-model="model"',
      'ng-required="true"'
    ];

    if (angular.isDefined(attrs.placeholder)) {
      attributes.push('placeholder="{{placeholder}}"');
    }

    var ngOptions = '';

    if (angular.isDefined(attrs.valueProperty)) {
      ngOptions += 'item.' + attrs.valueProperty + ' as ';
    }

    ngOptions += 'item.' + attrs.displayProperty + ' for item in source';
    ngOptions += '"';
    attributes.push('ng-options="' + ngOptions + '"');

    var html = '<select ' + attributes.join(' ') + '></select>';

    return html;
  }

});
so-select {
  position: relative;
}

so-select select {
  font-family: 'Helvetica';
  display: inline-block;
  height: 24px;
  width: 200px;
  padding: 0 1px;
  font-size: 12px;
  color: #222;
  border: 1px solid #c7c7c7;
  border-radius: 4px;
}

so-select.empty:before {
  font-family: 'Helvetica';
  font-size: 12px;
  content: attr(placeholder);
  position: absolute;
  pointer-events: none;
  left: 6px;
  top: 3px;
  z-index: 0;
  color: #888;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="soDemo" ng-controller="soDemoController">
  <so-select value-property="id" display-property="name" source="vm.names" ng-model="vm.nameId" placeholder="(select name)"></so-select>
</div>

查看更多
呛了眼睛熬了心
5楼-- · 2018-12-31 03:39

If you are using angular go like this

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

查看更多
路过你的时光
6楼-- · 2018-12-31 03:40

For a required field, there is a pure-CSS solution in modern browsers:

select:required:invalid {
  color: gray;
}
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>

查看更多
怪性笑人.
7楼-- · 2018-12-31 03:41

User should not see the placeholder in select options. I suggest to use hidden attribute for placeholder option and you don't need 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>

查看更多
登录 后发表回答