开发者

How to change element class on select option using jQuery [duplicate]

This question already has answers here: 开发者_StackOverflow中文版 How to dynamically add class when I select option (8 answers) Closed 1 year ago.

I want change my class="value" on select option using jQuery

Example

<select name="color_scheme" id="color_scheme">
  <option selected="selected">Default</option>
  <option>Black</option>
  <option>Blue</option>
  <option>Brown</option>
  <option>Green</option>
  <option>Gray</option>
  <option>Lime</option>
  <option>Orange</option>
</select>

<span class="Default"></span>

If we select Black span class will be

<span class="Black"></span>

Let me know


I achieved this by storing the default class, and removing that class whenever the select changes.

var selectedScheme = 'Default';

$('#color_scheme').change(function(){
    $('span').removeClass(selectedScheme).addClass($(this).val());
    selectedScheme = $(this).val();
});

A working example can be found here: http://jsfiddle.net/9PeAc/1/


use the change event to determine when the user selected another option. To remove all current classes, call removeClass() with no arguments. Finally add the new class, which can be accessed by this.value.

$('#color_scheme').change(function(e) {
    $('span').removeClass().addClass(this.value);
});

Demo: http://www.jsfiddle.net/4yUqL/100/


Try:

$('p').removeClass('myClass noClass').addClass('yourClass');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜