Limit the number of characters in a select HTML / CSS / JS field

1

I know that using the maxlength attribute it is possible to limit the amount of characters of a input .

Doubt: This property applies to select , otherwise what would be its equivalent, or how to achieve the same goal.

<select maxlength="5">
  <option value="opcao" maxlength="5">123456789</option>
</select>

Note that in the code above the attribute does not work, so how do I proceed?

    
asked by anonymous 24.08.2016 / 17:27

1 answer

2

You can use Javascript for this:

(function(){
  var selects = document.querySelectorAll('[data-limit]');
  
  // percorre a lista de selects
  [].forEach.call(selects, function(select){
    
    var limit = select.getAttribute('data-limit');
    
    // percorre a lista de options do select
    [].forEach.call(select.options, function(option){
      var text = option.innerHTML.substring(0, limit);
      option.innerHTML = text;
    });
  });
})();
<select data-limit='5'>
  <option>123</option>
  <option>1234567890</option>
  <option>123456</option>
</select>

<select data-limit='2'>
  <option>4321</option>
  <option>1234567890</option>
  <option>123</option>
</select>
    
24.08.2016 / 19:10