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.
- 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/
本文标签: javascriptHighlight Selected Option Using jQueryStack Overflow
版权声明:本文标题:javascript - Highlight Selected Option Using jQuery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745282788a2651522.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论