Pregunta

Having some trouble with trying to dynamically add and remove classes to a div based on radio selection. Essentially, I'm attempting to have a second header area that can be dynamically changed based on radio selections.

The HTML:

<!-- Headers -->

<div class="header">
    <p>I'm a header</p>
</div>
<div class="extra-header header-hidden">
    <p>I'm an extra header</p>
</div>

<!-- Radio Buttons -->

<div class="radio-inline">
    <label>
        <input type="radio" name="headerChoice" class="trigger" id="headerOptionActivate" value="activate" checked />
          Off
    </label>
</div>
<div class="radio-inline">
    <label>
        <input type="radio" name="headerChoice" class="trigger" id="headerOptionSmall" value="small"  />
          s
    </label>
</div>
<div class="radio-inline">
    <label>
        <input type="radio" name="headerChoice" class="trigger" id="headerOptionMedium" value="medium" />
          m
    </label>
</div>
<div class="selection-wrap">
    <div class="radio-inline">
        <label>
            <input type="radio" name="headerChoice" class="trigger" id="headerOptionLarge" value="large" />
          L
        </label>
    </div>
</div>

The Javascript (using jQuery)

$('.trigger').change(function(){
    $('.extra-header').removeClass('header-hidden');
    $('.extra-header').toggleClass('header-' + $(this).val());
});

Here's a fiddle of the problem: http://jsfiddle.net/A3zeS/1/

As you can see, the classes are currently being added, they're just not being removed. I've tried numerous variations of jquery but haven't been able to figure it out. Much obliged for any insight.

¿Fue útil?

Solución

You're looking for something like this

$('.trigger').on('change', function () {
    $('.extra-header').toggleClass('header-hidden', $('#headerOptionActivate').is(':checked'));

    $('.trigger').each(function() {
        $('.extra-header').toggleClass('header-' + this.value, this.checked);
    });
});

FIDDLE

Otros consejos

try

$('.extra-header').removeClass().addClass('extra-header').addClass('header-' + $(this).val())

http://jsfiddle.net/A3zeS/1/

If the other classes are static and won't change then

$('.trigger').change(function () {
    $('.extra-header').removeClass('header-hidden');
    $('.extra-header').removeClass().addClass('extra-header header-' + $(this).val());
});

Demo: Fiddle

else

$('.trigger').change(function () {
    var self = this;
    $('.extra-header').removeClass('header-hidden').attr('class', function (i, clazz) {
        return clazz.replace(/header-[^\s]+/g, '') + ' header-' + self.value;
    });
});

You could use following snippet:

DEMO jsFiddle

$('.trigger').change(function () {
    var self = this;
    $('.extra-header').toggleClass(function (_, c) {
        return c.match(/ header-\w+/)[0] + ' header-' + (self.value !== "activate" ? self.value:"hidden")
    });
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top