Pergunta

Hello guys i'm trying to create a jquery function when he click the select button on the first time the background will change to white and if he click again it will change to blue vice versa

<select name="contact" class="changeBg">
     <option value="">Change!</option>
     <option value="">Changes!</option>
</select>

$('.changeBg').click(function() {
    $(this).css('background-color', 'green');
 });
Foi útil?

Solução

You can try using .toggleClass( className, switch ) to switch between two classes.

Live Demo

$('.changeBg').click(function() {
    $(this).toggleClass('white blue');
});

Outras dicas

Try to toggle it with name like

$('select[name="contact"]').change(function(){
     $(this).toggleClass('class1 class2');
});

For the both classes you can give background colors as like

.class1 {background-color:pink;}
.class2 {background-color:white;}

Even you can choose class name as like

$('.changeBg').change(function(){
     $(this).toggleClass('class1 class2');
});

But better you can switch or toggle 2different classes ratherthan the changebg.Because if you toggle that class then for the second time the change event wont be work.

Fiddle Demo

.toggleClass()

$('.changeBg').click(function() { //you can use change event
    $(this).toggleClass('BgColor');
});

CSS

.changeBg { /* no need if your background is already white */
    background-color:#fff;
}
.BgColor {
    background-color:blue;
}
$(function () {
        $('.changeBg').change(function () {
            $(this).toggleClass('whileClass BlackClass');
        });
    });

    .whileClass {
        background-color: pink;
    }

    .BlackClass {
        background-color: white;
    }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top