2

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.

4

4 回答 4

1

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')
    })
})
于 2013-05-30T20:18:36.643 回答
1

Remove the class from the other elements first.

Fork: http://jsfiddle.net/CzuGF/

Line 3:

$('select option').removeClass('highlight');
于 2013-05-30T20:18:46.287 回答
1

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.net/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');
    })
})
于 2013-05-30T20:27:10.563 回答
0

Add this line in your code, before you add the class.

$(this).find(".highlight").removeClass("highlight");

Demo: http://jsfiddle.net/tymeJV/t4Vhd/2/

于 2013-05-30T20:17:45.377 回答