admin管理员组

文章数量:1418081

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.

Share Improve this question edited May 30, 2013 at 20:46 qJake 17.1k17 gold badges87 silver badges137 bronze badges asked May 30, 2013 at 20:15 kaoscifykaoscify 1,7537 gold badges38 silver badges76 bronze badges 2
  • 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
Add a ment  | 

4 Answers 4

Reset to default 1

Remove 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/

本文标签: javascriptHighlight Selected Option Using jQueryStack Overflow