I'm trying to highlight the selected value from a dropdown list, which works... but when you select another item from the list, that gets highlighted as well. It keeps on adding to other items as you select them. How do I remove it from the old <option>
when the new <option>
is selected? Check out my JSFiddle here. I know I'm supposed to use an if/else
statement, but not sure how.
I'm trying to highlight the selected value from a dropdown list, which works... but when you select another item from the list, that gets highlighted as well. It keeps on adding to other items as you select them. How do I remove it from the old <option>
when the new <option>
is selected? Check out my JSFiddle here. I know I'm supposed to use an if/else
statement, but not sure how.
- Wow, thanks for the quick responses everyone. – kaoscify Commented May 30, 2013 at 20:36
-
If you post a good, well explained, relatively simple question, people usually answer within a couple of minutes, tops.
:)
– qJake Commented May 30, 2013 at 20:45
4 Answers
Reset to default 1Remove the class from the other elements first.
Fork: http://jsfiddle/CzuGF/
Line 3:
$('select option').removeClass('highlight');
see the demo
var highlighted="";
$(function () {
$('#places').change(function () {
//if there is a previous selection, then remove highlight class
if(highlighted!="")
$('select option:contains(' + highlighted+ ')').removeClass('highlight')
//store the current selection in temp var
highlighted=$(this).val();
$('select option:contains(' + $(this).val() + ')').addClass('highlight')
})
})
This code work like a charm and can be reused if you have multiple select
:
$(function () {
$('select').change(function () { //Can change the selector to you input class if you want, doesnt matter
$(this).find('.highlight').removeClass('highlight');
$(this).find('option:contains(' + $(this).val() + ')').addClass('highlight');
})
})
Fiddle : http://jsfiddle/t4Vhd/5/
OR
$(function () {
$('select').change(function () { //Can change the selector to you input class if you want, doesnt matter
$(this).find('option:contains(' + $(this).val() + ')').addClass('highlight').siblings().removeClass('highlight');
})
})
Add this line in your code, before you add the class.
$(this).find(".highlight").removeClass("highlight");
Demo: http://jsfiddle/tymeJV/t4Vhd/2/
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745282788a4620377.html
评论列表(0条)