Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a class select option is not selected

When i select something from a selectbox it adds a class to the

selected option this way:

$(
    'div#tabs input[type="text"],
    select option:selected,
    input:checked,
    textarea'
).addClass('takethis');

But when I select a different option it doesn't remove the class takethis from the option which I first selected. How can I force this?

like image 875
sanders Avatar asked Dec 04 '22 15:12

sanders


2 Answers

Remove class from all non-selected options:

$("select option:not(:selected)").removeClass("takethis");

Then add to selected one:

$("select option:selected").addClass("takethis");
like image 71
Seb Avatar answered Dec 11 '22 16:12

Seb


You could use removeClass like this:

$('#tabs').find('option').removeClass('takethis');

I am not sure what you are trying to do, though. This code:

$('div#tabs input[type="text"],
            select option:selected,
            input:checked,
            textarea').addClass('takethis');

Is grabbing all text fields, the selected option of all selects, all checked fields, and all textareas and adding the class takethis to it. Is that what you want to do?

EDIT I see what you're trying to do. If that is the case, why not just do this?

var table = $('<table>');
$('div#tabs :input').each(function() {
    var val = $.trim($(this).val());
    var name = $(this).attr('name');
    if(val) {
        var td1 = $('<td>').html(name);
        var td2 = $('<td>').html(val);
        $('<input>').attr({
            type: 'hidden',
            name: name
        }).appendTo(td2);
        $('<tr>').append(td1).append(td2).appendTo(table);
    }
});
$('#4tab').append(table);

Wouldn't this be simpler or am I missing a requirement here?

like image 45
Paolo Bergantino Avatar answered Dec 11 '22 16:12

Paolo Bergantino