Set width of dropdown element in HTML select dropdown options - html

I am working on a website that involves automatically populating a select box using a PHP script. This all works fine except the problem is that what I am using to populate the text box have very long titles (they are journal articles and presentation titles). The dropdown box extends to the width of the longest element, which stretches off the edge of the screen, therefore making the scrollbar impossible to reach. I have tried various methods of trying to manually set the dropdown box using CSS to a particular width, but so far to no avail. The best I have accomplished it to set the Select box to a certain width but the dropdown menu itself is much, much wider.
Any tips on this would be greatly appreciated.
EDIT:
It turns out that the following CSS line works in all of the primary browsers except for Google Chrome (which is what I was testing the page in). If a solution for Chrome is known, that would be good to know about.
select, option { width: __; }

I find the best way to handle long dropdown boxes is to put it inside a fixed width div container and use width:auto on the select tag. Most browsers will contain the dropdown within the div, but when you click on it, it will expand to display the full option value. It does not work with IE explorer, but there is a fix (like is always needed with IE). Your code would look something like this.
HTML
<div class="dropdown_container">
<select class="my_dropdown" id="my_dropdown">
<option value="1">LONG OPTION</option>
<option value="2">short</option>
</select>
</div>
CSS
div.dropdown_container {
width:10px;
}
select.my_dropdown {
width:auto;
}
/*IE FIX */
select#my_dropdown {
width:100%;
}
select:focus#my_dropdown {
width:auto\9;
}

You can style (albeit with some constraints) the actual items themselves with the option selector:
select, option { width: __; }
This way you are not only constraining the drop-down, but also all of its elements.

On the server-side:
Define a max length of the string
Clip the string
(optional) append horizontal ellipsis
Alternative solution: the select element is in your case (only guessing) a single-choice form control and you could use a group of radio buttons instead. These you could then style with better control. If you have a select[#multiple] you could do the same with a group of checkboxes instead as they can both be seen as a multiple-choice form control.

HTML:
<select class="shortenedSelect">
<option value="0" disabled>Please select an item</option>
<option value="1">Item text goes in here but it is way too long to fit inside a select option that has a fixed width adding more</option>
</select>
CSS:
.shortenedSelect {
max-width: 350px;
}
Javascript:
// Shorten select option text if it stretches beyond max-width of select element
$.each($('.shortenedSelect option'), function(key, optionElement) {
var curText = $(optionElement).text();
$(this).attr('title', curText);
// Tip: parseInt('350px', 10) removes the 'px' by forcing parseInt to use a base ten numbering system.
var lengthToShortenTo = Math.round(parseInt($(this).parent('select').css('max-width'), 10) / 7.3);
if (curText.length > lengthToShortenTo) {
$(this).text('... ' + curText.substring((curText.length - lengthToShortenTo), curText.length));
}
});
// Show full name in tooltip after choosing an option
$('.shortenedSelect').change(function() {
$(this).attr('title', ($(this).find('option:eq('+$(this).get(0).selectedIndex +')').attr('title')));
});
Works perfectly. I had the same issue myself. Check out this JSFiddle http://jsfiddle.net/jNWS6/426/

Small And Best One
#test{
width: 202px;
}
<select id="test" size="1" name="mrraja">

u can simply use "width" attribute of "style" to change the length of the dropdown box
<select class="my_dropdown" id="my_dropdown" style="width:APPROPRIATE WIDTH IN PIXLES">
<option value="1">LONG OPTION</option>
<option value="2">short</option>
</select>
e.g.
style="width:200px"

Small And Better One
var i = 0;
$("#container > option").each(function(){
if($(this).val().length > i) {
i = $(this).val().length;
console.log(i);
console.log($(this).val());
}
});

Related

How to do pagination in select box based on scroll

HTML
<select class="form-control choice requiredField" id-available name="SelectData" ng-model="box.box_id" title="Select">
<option value="" disabled selected>{{'_SELECT_BEACON_' | i18n}}</option>
<option value="{{y.box_id}}" ng-repeat="y in dataList" class="nms">{{y.beacon_code}}</option>
</select>
ANGULARJS
boxService.listUnassignedDevice(function(res) {
$scope.dataList = res;
}, function(error) {
});
Here I have large data in "dataList"(10000>). So I need to list data in select box after mouse scroll down. First I have to show 100 data, when mouse scroll down, I need to show next 100 data from API.
you can use ngInfiniteScroll directive and add script tag then add module 'infinite-scroll'and then Use the directive by specifying an infinite-scroll attribute on an element.
<div infinite-scroll="myPagingFunction()" infinite-scroll-distance="3"></div>
ngInfiniteScroll will call myPagingFunction() any time the bottom of
the element approaches the bottom of the browser window. See the API
documentation for more information about what attributes are available
for use, and take a look at the demos to see ngInfiniteScroll in
action.

CSS for <select> menu works ... sometimes

This is bizarre. I have a select menu that I've styled to display a hierarchical list.
I have multiple Firefox profiles setup to simulate multiple sessions. One is my "main" profile with numerous extensions and customizations.
However, this is what my styled menu looks like in my "main" profile while using safe mode:
(EDIT: Firefox's safe mode that disables the extensions and resets the configuration)
This is what it looks like in a clean, de-cached Firefox profile:
For comparison's sake, Chrome and IE make it half-way there:
I've already got -moz-appearance: none and -webkit-appearance:none; for both the <select> and <option> elements. The left offset on the options is achieved using padding-left.
The most perplexing thing is how this works in one Firefox profile (in safe mode) but not a completely clean one.
How do I make this consistently like the first example across all browsers?
Edit: fiddle
It seems to me you have 3 options:
Pure Html:
Add in blank non-breaking spaces before your options in the lower levels and do it that way : not exactly kind to your time, and a bit messy-looking, but would work.
Pure CSS:
Add on an additional class depending on the level ( doesn't seem to work - already tried it )
Jquery/Javascript: Probably the quickest way! If you are willing to use jquery [or you could do it in plain js, but I've done the fiddle using jquery..]:
Add in a hierarchy indicator using additional classes, depending on the level of the hierarchy See fiddle or snippet
$(document).ready(
function() {
$('.l2').each(
function() {
$(this).text('--' + $(this).text());
}
);
$('.l3').each(
function() {
$(this).text('----' + $(this).text());
}
);
}
);
#hierarchy,
#hierarchy>option {
text-align: justify;
text-shadow: 1px 1px grey; /*optional!*/
word-spacing: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="hierarchy" name="hierarchy">
<option class="l1" selected>Level 1</option>
<option class="l2">First L2 Indent</option>
<option class="l3">First L3 Indent</option>
<option class="l2">Second L2 Indent</option>
<option class="l3">Second L3 Indent</option>
<option class="l3">Third L3 Indent</option>
</select>

How can I change color of a select option with CSS on hover?

<select style="width:245px;">
<option value="rseleccionar">Seleccione..</option>
<option value="bs">Bienes Separados</option>
<option value="bm">Bienes Mancomunados</option>
</select>
I want to change the blue color of default for another.
Styling select and option tag is very limited.
This is because the way they are displayed may change according to the browser/the OS. Think about what happens when you click a select tag on your phone. You don't get a dropdown list as expected on a desktop browser. So you couldnt style something universal as it doesn't natively display the save everywhere.
Styling possibilities are: mainly on the select tag but very restricted on the option. You could for example disable the native style of the select box:
select {
appearance: none;
/* may need vendors prefixes. */
}
Other solution is: jQuery plugins that simulate select box using other HTML tags:
https://jqueryui.com/selectmenu/
https://github.com/marcj/jquery-selectBox
And all that Google may return you with keywords "jQuery select box" :)
Option elements are rendered by the OS, not HTML. You cannot change the style for these elements.
Try this, hope it'll work
<select class="hover_color" style="width:245px;">
<option value="rseleccionar">Seleccione..</option>
<option value="bs">Bienes Separados</option>
<option value="bm">Bienes Mancomunados</option>
</select>
.hover_color:hover { background-color: red; border:1px solid red }

Chrome bug on select element dropdown when many options are hidden

I'm looking for a workaround for a rendering bug in Chrome. It shows up when a select element has about 90%+ hidden option elements. In Chrome, the dropdown height becomes too short to use. This does not appear to happen on other browsers. View example on jsFiddle.
HTML Example
Note: Some options were removed to keep the code brief.
The bug does not show up unless all options are present.
100 Options, 90% Hidden:<br>
<select>
<option value="">Select an Option</option>
<option value="0" style="display: none">Option 0</option>
<option value="1" style="display: none">Option 1</option>
<option value="2" style="display: none">Option 2</option>
<option value="3" style="display: none">Option 3</option>
<!-- Options removed for brevity. -->
<option value="86" style="display: none">Option 86</option>
<option value="87" style="display: none">Option 87</option>
<option value="88" style="display: none">Option 88</option>
<option value="89" style="display: none">Option 89</option>
<option value="90">Option 90</option>
<option value="91">Option 91</option>
<option value="92">Option 92</option>
<option value="93">Option 93</option>
<option value="94">Option 94</option>
<option value="95">Option 95</option>
<option value="96">Option 96</option>
<option value="97">Option 97</option>
<option value="98">Option 98</option>
<option value="99">Option 99</option>
</select>
Browsers Tested:
Chrome 27 & 28 (Fail)
Firefox 21 (Pass)
IE 9 (Pass)
Opera 12 (Pass)
Safari 5.1 (Pass)
View Example on jsFiddle
Alternate Example Link
Update: I did some reading on the subject, and apparently options are not supposed to be hidden within a select. You can disable options, but they will not disappear. If you don't want an option to be in the select at all, you're supposed to remove the node entirely. The ability to hide options doesn't appear to work completely cross-browser, and in most you can continue to select the "hidden" options by using the arrow keys. I need to toggle options on and off, which makes this inconvenient to my particular situation, but this appears to be the only method that will work thus far.
Adding this might be considered a workaround:
$(document).ready(function () {
$('#ph2').mouseenter(function () {
var html = '';
$(this).find('option').each(function () {
if ($(this).css('display') !== 'none') {
html = html + '<option>' + $(this).text() + '</option>';
}
});
$(this).html(html);
})
});
Here's the jsFiddle; I'm using jquery just for simplicity. In this case, I'm just redoing the HTML on mouseenter. It's not ideal but it could get you going further. Also, note that you have ph2 set up as a div in your HTML; I think you should set it as a select element from the start and on the fiddle you can see the change I made to the html. But overall, until the bug is fixed, I think something like this is going to be as close as you'll get to having a working option.
The problem is already active on all major browser (Edge, Chrome, Opera,....) but Firefox.
The problem arises as soon as the number of hidden items is greater than 1000.
Be careful, because with just 100 items, all browser seem to work
The problem also disappears if the active items (not hidden, not disabled) are at the top of the list.
More exactly, when you click on the "select" input field, the browser open a list with a number of rows that is equal to the number of active items included in the first 1000 item.
For example, if you build a list of items with first x items active, then y items "inactive" (where y if greater than 1000) and then again z items active, you will see a list wide x rows with x+z items.
By the way, a workaround to the problem could be the sorting of the items list
This behaviour has been verified on Chrome, Opera, Edge
As a workaround for this bug I can propose the following solution:
To hide an option 'convert' it to some other tag and hide it with .hide().
To show an option 'convert' it back to option and show it with .show().
For 'conversion' we need something like this: https://stackoverflow.com/a/9468280.
Example:
// some `replaceTagName` implementation here
// hiding options
$('.option-selector').replaceTagName('span').hide();
// showing options
$('.option-selector').replaceTagName('option').show();
A bit heavy but working :)
I had this problem and this is what I did:
var originalSelect = $("#the_select").clone();
function hideSomeOptions(){
$('#the_select .hide_me').remove();
}
function restoreAllOptions(){
$("#the_select").replaceWith(originalSelect[0]);
}
The target select input has the ID "the_select" and the options or optgroups that need to be toggled have the "hide_me" class.
I found that the order of the hidden/visible options make a difference. It is like chrome stops counting for the height for the drop down at the first hidden option. One way around is to move the shown options to the top of the select. If you are using jquery something like this.
var select = "select#MySelect";
$(select).children("option").hide(); //hide all options
$(select).children("Selector for items to show").each(function(idx, elm) {
$(elm).parent().prepend(elm); //move item to the top of parent
});
$(select).children("Selector for items to show").show(); //show selected options
I ran into the same problem (Chrome 40) and found that the following workaround works well for me.
var originalOptions = [];
$(document).ready(function(){
originalOptions = $("yourSelect").children("option");
$("someElement").someEvent(function(){
$("yourSelect").children("option").remove();
$(originalOptions).each(function(){
if(/*criteria here*/){$("yourSelect").append($(this));}
});
});
});
The best fix is to add at the end on the last
<option></option> in your Select Element. Add this code:
<optgroup></optgroup>
This will add a blank group element, and for now is the best Easy and fast FIX to this rare BUG.
Thanks!

Is there a way to hide a SELECT based on the value of another SELECT using only CSS?

I have 2 SELECT elements, but I only want to display the second if the first has a specific value.
I know how to do this with javascript, but I was hoping I could use an adjacent sibling selector to accomplish this with pure HTML/CSS:
<style>
select[name=select2] { display:none; }
select[value=show] + select[name=select2] { display:auto; }
</style>
<select name="select1">
<option value="show">Show Select 2</option>
<option value="hide">Hide Select 2</option>
</select>
<select name="select2">
</select>
Unfortunately, I can't get this to work. I imagine it's because value isn't a real attribute of a SELECT, but I'm not sure. Any ideas what is going on here?
Here's a fiddle to test with:
http://jsfiddle.net/rr24g/
no, totally impossible, because css is "cascading" you can't go upwards
/* pseudo code - doesn't work, just demonstrating the problem */
select[name=select1] > option[value=show][selected] ::parent:: + select[name=select2]
you need javascript!
I'm going to say "No". You're coding UI based on business logic specifically. CSS wasn't designed for that. Keep it in javascript.
You might be able to do something with :hover using the top level selects.
Otherwise, I think a js solution is in order.