Display a description for each select option jquery
I have run into a problem and would appreciate help devising a creative, and lightweight approach around it. I need to show descriptive text every time user selects on option from a select list. I would use something like:
开发者_运维百科$('#description').html($(this).attr('title') );
But the title tag is used by a plugin called msDropdown(a skinning plugin) and seems to not function as usual because of it.
Any help is appreciated.
If I were you, I would avoid using the title
attribute. That's not what it's for. Use custom data-
attributes instead -- they make syntactic sense, are valid HTML under HTML5 and function happily in all browsers, and jQuery integrates them into its data()
functionality.
For instance:
HTML:
<select id="mySelect">
<option value="1" data-description="Item 1">Item 1</option>
<option value="2" data-description="Item 2">Item 2</option>
<option value="3" data-description="Item 3">Item 3</option>
</select>
<span id="description"></span>
jQuery:
$('#mySelect').change(function(){
var $selected = $(this).find(':selected');
$('#description').html($selected.data('description'));
}).trigger('change'); // run handler immediately
See jsFiddle example.
I'd take a slightly different approach, and use a pairing between the select
list and an ol
(or any other element):
html:
<select id="selectElement" id="selectElement">
<optgroup label="Select a fruit">
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
</optgroup>
</select>
<ol id="explanatoryText">
<li>The first option chooses 'apples.'</li>
<li>This option chooses 'oranges' instead.</li>
</ol>
css:
ol#explanatoryText li {
display: none;
}
ol#explanatoryText li.descriptor {
display: list-item;
}
jQuery:
$('#selectElement').click(
function(){
$(this).change();
});
$('#selectElement').change(
function(){
var index = $(this).find('option:selected').index();
$('#explanatoryText li.descriptor').removeClass('descriptor');
$('#explanatoryText li').eq(index).addClass('descriptor');
});
JS Fiddle demo.
精彩评论