Ad
How To Make The Selected Option The Width Of The Current Selected Option's Text?
I am trying to make the Select Option to have the width of the current Selected Option.
My code is the standard HTML for a Select Option dropdown:
<select name="search_options">
<option value="all">All</option>
<option value="entertainment">Entertainment</option>
<option value="newsandpolitics">News & Politics</option>
<option value="sports">Sports</option>
<option value="lifestyle">Lifestyle</option>
<option value="health">Health</option>
<option value="scienceandtech">Science & Tech</option>
</select>
I have been trying to do this with just CSS or Javascript, with no JQuery, and I can't figure it out.
I have found several fiddles with JQuery already, but no CSS/Javascript ones.
Is there any way to achieve this, identical with the above 2 fiddles, using just CSS or pure Javascript?
Any pointers in the right direction would be great.
Ad
Answer
Based on your second link you can do it like this:
var selectId = document.getElementById("yourSelect");
selectId.onchange=function(){
var selectedValue = selectId.options[selectId.selectedIndex].value;
var selectedText = selectId.options[selectId.selectedIndex].text;
selectId.style.width = 20 + (selectedText.length * 8) + "px";
}
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad